/ / Usando gli intervalli come chiavi in ​​Ruby - ruby, range

Usando gli intervalli come chiavi in ​​Ruby - ruby, range

Ho una tabella hash che utilizza gli intervalli come chiavi.

hash = {
1..10 => "Foo",
11..20 => "Bar",
21..30 => "Baz",
31..40 => "Quux",
}

hash.find {|key, value| key == 5} # => `nil`

Perché non torna Foo?

MODIFICARE:

Come sottolineato di seguito, cambiato Hash a hash

risposte:

2 per risposta № 1

Con == controlli una vera uguaglianza e 5 non è un intervallo. Ma puoi usare === o include?. Puoi anche provare select anziché find.

Esempio:

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"}

Si prega di vedere i diversi risultati. find restituisce un array, `seleziona un hash.

Un'osservazione conclusiva: hai usato Hash = .... Spero che questo sia un errore di battitura e che tu volessi usare hash.


1 per risposta № 2

case when le costruzioni sono progettate per fare questo.

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"

0 per risposta № 3

Per il tuo esempio specifico, potresti usare

Hash[(k-1)/10]

Ad esempio, se k = 15:

Hash[(15-1)/10] => Hash[1] => "Bar"

Nel caso generale, se la velocità è importante, prima costruisci un altro hash:

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"}

quindi puoi solo cercare valori:

H[15] #=> "Bar"
H[35] #=> "Quux"