DEV Community

alex
alex

Posted on

TIL .key method in Ruby

Earlier I attempted to create an array of keys using the .each method. But there is already a method to do so. In order to create an array of keys from a hash, you can use the .key method.

Example:

# Define a hash with some key-value pairs
user_info = {
  name: 'John Doe',
  age: 30,
  email: 'johndoe@example.com'
}

# Use the .keys method to get an array of keys
keys_array = user_info.keys

#the array will look like [:name, :age, :email]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)