I have a Ruby hash that looks like this:
h = {"side1"=>["green", "Green"], "side2"=>["verde", "Verde"]}
How can I get the first (or last) item at a particular key in the hash?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Actually, your example pseudo code in your question is correct.
For your hash
the keys are
'side1'and'side2'(with their values right of the hashrocket)So,
h['side2'].firstsays that for the value of key'side2', get the first element in the value["verde", "Verde"], which is an array.h['side2'][0]would also work. the aliasfirstis a convenience method.To get the last element of an array without having to know how big it is, use a negative index. e.g.
h['side2'][-1], which is equivalent toh['side2'][1]in this case.Note that keys in a hash are particular about whether it is a string or symbol. That is
h[:side2]would return nil, as the key hasn’t been set. Rails has a classHashWithIndifferentAccessthat treats symbols and strings as equivalent keys.EDIT
I should have mentioned that I tested my answer in
irb.irbis a great way to test your ideas about what may and may not work. In your terminal prompt, typeirb, enter, and play with ruby.