Introduction
Hashes store pairs of related information. These methods help you look at all the keys, all the values, or go through each pair one by one.
Hashes store pairs of related information. These methods help you look at all the keys, all the values, or go through each pair one by one.
hash.keys
hash.values
hash.each { |key, value| ... }keys returns an array of all keys.
values returns an array of all values.
each lets you run code for every key-value pair.
my_hash = {a: 1, b: 2, c: 3}
puts my_hash.keys.inspectmy_hash = {a: 1, b: 2, c: 3}
puts my_hash.values.inspectmy_hash = {a: 1, b: 2, c: 3}
my_hash.each { |key, value| puts "#{key} => #{value}" }This program shows how to get all keys, all values, and then prints each key with its value.
person = {name: "Anna", age: 30, city: "Paris"}
puts "Keys:"
puts person.keys.inspect
puts "Values:"
puts person.values.inspect
puts "Each key-value pair:"
person.each do |key, value|
puts "#{key}: #{value}"
endThe keys and values methods return arrays you can use like any other array.
The each method does not change the hash; it just lets you look at each pair.
keys gives you all the keys in an array.
values gives you all the values in an array.
each lets you do something with every key and value.
keys method do when called on a Ruby hash?keys methodkeys method extracts all keys from the hash and returns them as an array.values returns values, each iterates pairs, so only keys returns keys array.keys = keys array [OK]h?each{ |key, value| ... }.h.each { |key, value| puts key + value } uses correct syntax with pipes and comma. Others have syntax errors or wrong block format.h.each { |key, value| puts key + value } [OK]h = {a: 1, b: 2, c: 3}
h.keyskeys method on hashkeys method returns an array of all keys in the hash. Here keys are symbols :a, :b, :c.h = {x: 10, y: 20}
h.each do |k v|
puts "#{k}: #{v}"
end|k, v|. Here comma is missing.each do-end is valid, and puts syntax is correct.k and v -> Option Ah = {a: 1, b: 0, c: nil, d: 4}, which code snippet correctly returns an array of keys whose values are truthy (not false or nil)?select filters pairs by value truthiness.h.select { |k, v| v }.keys filters hash pairs by truthy value, then gets keys -> [:a, :d] [check]. h.keys.select { |k| k } checks if key truthy (all symbols are), returns all keys. h.values.select { |v| v }.keys calls keys on array (NoMethodError). h.each { |k, v| k if v }.keys returns original hash, no filtering.h.select { |k, v| v }.keys [OK]Pass the test and this pattern moves unknown