I am currently working on a project with Ruby. I don't know how to find the set of the value and key that has the same key as I gave with argument.
what I have tried is something like this below. but it doesn't work.
def find_target(type)
target = type_list.find{|k,v| k == type}
target
end
def type_list
type = {
a: 1,
b: 2,
c: 3,
d: 4
}
type
end
but instead of giving an argument of variable, I gave a string as an argument, and it worked.
def find_target(a)
target = type_list.find{|k,v| k == a}
target
end
How can I solve this?
I would love you if you could help me. Thank you.
I think one thing tripping you up is that your type_list
hash is keyed with symbols (rather than strings or the value of a variable). The syntax you're using:
{a: 1}
is just shorthand for this:
{:a => 1}
Which means "A Hash with one key: the symbol :a
with the value 1
". That's distinct from:
{'a' => 1} # Keyed with the string 'a'
and this:
a = 'something'
b = {a => 1} # Keyed with value of 'a' at the time of creating, ie: {'something' => 1}. Note that if you change the value of a, the hash key won't change.
What do you expect as your return value from find_target(:a)
? The find
method on a Hash will return an Enumerator - mostly equivalent to a two-element Array, with the key and the value: {a: 1}.find{|k,v|k ==:a}
will return [:a, 1]
. Is that what you want?
If you just want to have the value 1
returned, then you're really doing a hash lookup, and you don't need any extra methods at all. A common way to do this would be to define type_list
as a constant, and then just refer to it by key:
TYPE_LIST = {
a: 1,
b: 2,
c: 3,
d: 4
}
#Then to find the type:
TYPE_LIST[:a] # Returns '1'
You might want to use a find_type
method to handle the case where the key doesn't match a type: a plain Hash lookup will return nil
, which you might not want.
Hope this helps put you on the right path, but I'm happy to expand this answer if needed!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.