Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby Array key pair value?

Tags:

arrays

ruby

hash

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
like image 654
RajG Avatar asked Nov 13 '12 15:11

RajG


People also ask

How do I get the key-value in Ruby?

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.

How do you create a key-value pair in Ruby?

Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.

What does .select do in Ruby?

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.

How do you turn an array into a hash in Ruby?

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.


1 Answers

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
like image 127
Paul Richter Avatar answered Oct 18 '22 07:10

Paul Richter