In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.
Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.
hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.
Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.
Also, a bit simpler....
>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]
Ruby doc here
I would use:
hash.map { |key, value| value }
hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]]
Enumerable#collect
takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.
The Enumerable
module is pretty awesome. Knowing it well can save you lots of time and lots of code.
hash = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]
It is as simple as
hash.values
#=> [["a", "b", "c"], ["b", "c"]]
this will return a new array populated with the values from hash
if you want to store that new array do
array_of_values = hash.values
#=> [["a", "b", "c"], ["b", "c"]]
array_of_values
#=> [["a", "b", "c"], ["b", "c"]]
There is also this one:
hash = { foo: "bar", baz: "qux" }
hash.map(&:last) #=> ["bar", "qux"]
Why it works:
The &
calls to_proc
on the object, and passes it as a block to the method.
something {|i| i.foo }
something(&:foo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With