I have a Ruby hash that looks like this:
h = {"side1"=>["开发者_StackOverflowgreen", "Green"], "side2"=>["verde", "Verde"]}
How can I get the first (or last) item at a particular key in the hash?
Actually, your example pseudo code in your question is correct.
For your hash
h = {
"side1" => ["green", "Green"],
"side2" => ["verde", "Verde"]
}
the keys are 'side1'
and 'side2'
(with their values right of the hashrocket)
So, h['side2'].first
says 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 alias first
is 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 to h['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 class HashWithIndifferentAccess
that treats symbols and strings as equivalent keys.
EDIT
I should have mentioned that I tested my answer in irb
. irb
is a great way to test your ideas about what may and may not work. In your terminal prompt, type irb
, enter, and play with ruby.
I ran into a similar situation where I arbitrarily wanted the "first" entry from the hash for some test code. That's not exactly what this question is about, but it came up in the search I ran so figure it might do likewise for others.
Of course "first item" is arbitrary in a hash, but the keys method will return a list of all keys sorted by some magic. If you like that sort order, then you can get the "first" method with
h[h.keys.first]
Any hash has keys and values you can simply make
hash.values.first
hash.values.last
hash.keys.first
hash.keys.last
So you will have the array of values you want in case first or last
Yes. puts h["side2"].first
should work. I guess this goes to show that Ruby follows the principle of least-surprise, where your pseudo-code turned out to be the same as the actual code. :-)
精彩评论