I am trying to pair up two key value pairs but I am unsure how to accomplish this. Below is what I have attempted:
struc = Array[(3,4),(5,6)]
for i in 0..1
puts "#{struc[i,i]}"
end
But my desired output is the following (which the previous code block does not produce):
3 4
5 6
You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.
Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.
Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.
Why not use a hash. With it, you can do:
struc = {3 => 4, 5 => 6}
To output the result, you can use the each_pair method, like so:
struc.each_pair do |key, value|
puts "#{key} #{value}"
end
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