Find display value in array

J

Jon Stenqvist

Hi,

I have a array that looks like this
Type = [["key","value"],["key..","value.."],["..",".."]]

Now i want to the the display (value) when i have the key, is this a OK
way to do it? Or is there a better way?

Type.select{|key,disp| key == "H" }.collect{|key,value|value}.to_s
 
J

James Edward Gray II

Hi,

I have a array that looks like this
Type = [["key","value"],["key..","value.."],["..",".."]]

Now i want to the the display (value) when i have the key, is this
a OK
way to do it? Or is there a better way?

Yes. You want the assoc() method:
assoc_array = [%w[key1 value1], %w[key2 value2], %w[key3 value3]] => [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]
assoc_array.assoc("key2").last
=> "value2"

Hope that helps.

James Edward Gray II
 
H

Harry Kakueki

Type = [["key","value"],["key..","value.."],["..",".."]]
Now i want to the the display (value) when i have the key, is this a OK
way to do it? Or is there a better way?

Type.select{|key,disp| key == "H" }.collect{|key,value|value}.to_s
Is this what you want to do?
If so, I think iteration is easier than that.
I think it is also faster but I did not check.

arr = [["A",2],["H",3],["H",4]]
arr.each {|x| print x[1] if x[0] == "H"}

Harry
 
J

Jon Stenqvist

Thanks for a good solution!

Now i saw that i had may key on in the last position in the inner array,
is there someother function that i use insted, so i can search for last
item? and return the first.

James said:
Hi,

I have a array that looks like this
Type = [["key","value"],["key..","value.."],["..",".."]]

Now i want to the the display (value) when i have the key, is this
a OK
way to do it? Or is there a better way?

Yes. You want the assoc() method:
assoc_array = [%w[key1 value1], %w[key2 value2], %w[key3 value3]] => [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]
assoc_array.assoc("key2").last
=> "value2"

Hope that helps.

James Edward Gray II
 
F

Florian Gross

Now i saw that i had may key on in the last position in the inner array,
is there someother function that i use insted, so i can search for last
item? and return the first.

Try rassoc. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,311
Members
47,983
Latest member
Derek9890

Latest Threads

Top