ruby array hash get key by value and value by key
ruby array hash get key by value and value by key
我有散列{ "1" => "one", "2" => "two", "3" => "three" }
如何按值取键和按键取值
如果我通过“1”,我得到 "one",如果我通过 "two",我得到“2”
def finder (string)
table = { "1" => "one", "2" => "two", "3" => "three" }
*magick*
}
return string
end
puts finder("1") => one
puts finder("one") => 1
Hash#key
returns 给定值的键:
@hash = {"1"=>"one", "2"=>"two", "3"=>"three"}
@hash.key("one") #=> "1"
或 nil
如果不存在这样的值:
@hash.key("four") #=> nil
要获取键的值或值的键,您可以使用:
def finder(str)
@hash[str] || @hash.key(str)
end
finder("1") #=> "one"
finder("one") #=> "1"
如果您的散列很大并且您将重复执行此操作,您可以创建一个新的散列以进行快速查找:
h = {"1"=>"one", "2"=>"two", "3"=>"three"}
nh = h.merge h.invert
#=> {"1"=>"one", "2"=>"two", "3"=>"three", "one"=>"1", "two"=>"2", "three"=>"3"}
我有散列{ "1" => "one", "2" => "two", "3" => "three" }
如何按值取键和按键取值
如果我通过“1”,我得到 "one",如果我通过 "two",我得到“2”
def finder (string)
table = { "1" => "one", "2" => "two", "3" => "three" }
*magick*
}
return string
end
puts finder("1") => one
puts finder("one") => 1
Hash#key
returns 给定值的键:
@hash = {"1"=>"one", "2"=>"two", "3"=>"three"}
@hash.key("one") #=> "1"
或 nil
如果不存在这样的值:
@hash.key("four") #=> nil
要获取键的值或值的键,您可以使用:
def finder(str)
@hash[str] || @hash.key(str)
end
finder("1") #=> "one"
finder("one") #=> "1"
如果您的散列很大并且您将重复执行此操作,您可以创建一个新的散列以进行快速查找:
h = {"1"=>"one", "2"=>"two", "3"=>"three"}
nh = h.merge h.invert
#=> {"1"=>"one", "2"=>"two", "3"=>"three", "one"=>"1", "two"=>"2", "three"=>"3"}