使用范围作为 Ruby 中的键
Using ranges as keys in Ruby
我有一个使用范围作为键的哈希 table。
hash = {
1..10 => "Foo",
11..20 => "Bar",
21..30 => "Baz",
31..40 => "Quux",
}
hash.find {|key, value| key == 5} # => `nil`
为什么不 return Foo
?
编辑:
如下所述,将 Hash
更改为 hash
在 ==
中,您检查是否真正相等,而 5 不在范围内。但您可以使用 ===
或 include?
。您也可以尝试 select
而不是 find
.
示例:
hash = {
1..10 => "Foo",
11..20 => "Bar",
21..30 => "Baz",
31..40 => "Quux",
}
p hash.find {|key, value| key === 5} #[1..10, "Foo"]
p hash.find {|key, value| key.include?(5)} #[1..10, "Foo"]
p hash.select{|key, value| key === 5} #{1..10=>"Foo"}
p hash.select{|key, value| key.include?(5)}#{1..10=>"Foo"}
请查看不同的结果。 find
returns 一个数组,`select 一个哈希。
结束语:您使用了 Hash = ...
。我希望这是一个打字错误,你想使用 hash
。
case when
构造就是为此而设计的。
x = 5
p case x
when 1..10 then "Foo"
when 11..20 then "Bar"
when 21..30 then "Baz"
when 31..40 then "Quux"
end
# => "Foo"
对于您的具体示例,您可以使用
Hash[(k-1)/10]
例如,如果 k = 15
:
Hash[(15-1)/10] => Hash[1] => "Bar"
对于一般情况,如果速度很重要,首先构造另一个散列:
H=Hash.flat_map { |r,v| r.to_a.product([v]) }.to_h
#=> { 1=>"Foo" , 2=>"Foo" ,..., 10=>"Foo",
# 11=>"Bar" , 12=>"Bar" ,..., 20=>"Bar",
# ...
# 31=>"Quux", 32=>"Quux",..., 40=>"Quux"}
这样您就可以查找值:
H[15] #=> "Bar"
H[35] #=> "Quux"
我有一个使用范围作为键的哈希 table。
hash = {
1..10 => "Foo",
11..20 => "Bar",
21..30 => "Baz",
31..40 => "Quux",
}
hash.find {|key, value| key == 5} # => `nil`
为什么不 return Foo
?
编辑:
如下所述,将 Hash
更改为 hash
在 ==
中,您检查是否真正相等,而 5 不在范围内。但您可以使用 ===
或 include?
。您也可以尝试 select
而不是 find
.
示例:
hash = {
1..10 => "Foo",
11..20 => "Bar",
21..30 => "Baz",
31..40 => "Quux",
}
p hash.find {|key, value| key === 5} #[1..10, "Foo"]
p hash.find {|key, value| key.include?(5)} #[1..10, "Foo"]
p hash.select{|key, value| key === 5} #{1..10=>"Foo"}
p hash.select{|key, value| key.include?(5)}#{1..10=>"Foo"}
请查看不同的结果。 find
returns 一个数组,`select 一个哈希。
结束语:您使用了 Hash = ...
。我希望这是一个打字错误,你想使用 hash
。
case when
构造就是为此而设计的。
x = 5
p case x
when 1..10 then "Foo"
when 11..20 then "Bar"
when 21..30 then "Baz"
when 31..40 then "Quux"
end
# => "Foo"
对于您的具体示例,您可以使用
Hash[(k-1)/10]
例如,如果 k = 15
:
Hash[(15-1)/10] => Hash[1] => "Bar"
对于一般情况,如果速度很重要,首先构造另一个散列:
H=Hash.flat_map { |r,v| r.to_a.product([v]) }.to_h
#=> { 1=>"Foo" , 2=>"Foo" ,..., 10=>"Foo",
# 11=>"Bar" , 12=>"Bar" ,..., 20=>"Bar",
# ...
# 31=>"Quux", 32=>"Quux",..., 40=>"Quux"}
这样您就可以查找值:
H[15] #=> "Bar"
H[35] #=> "Quux"