1

私には4つのサイズがあり、それぞれが平方フィート単位でハッシュされています。

# The sizes. Sizes are in sq ft (min, max)
size_hash = {
  'Large'  => [70,139],
  'Medium' => [15,69],
  'Small'  => [1,14]
}

番号が与えられた場合、配列からサイズとして40返すにはどうすればよいですか?Medium

私はこのようなことをする必要がありますか?:

# The sizes. Sizes are in sq ft (min, max)
size_hash = {
  [70..139]  => 'Large',
  #... etc
}
4

4 に答える 4

5

あなたはprocを使うことができます:

size_store = proc{ |n|
  case n
  when 70..139
    'Large'
  when 15..69
    'Medium'
  when 1..14
    'Small'
  end
}
# USAGE: size_store[40]
于 2012-11-25T04:04:00.300 に答える
4
size_hash.find{|_, (min, max)| (min..max) === 40}[0]
# => "Medium"

しかし、そもそも最小値と最大値ではなく範囲を保存する方が良いと思います。

size_hash = {
    'Large'  => 70..139,
    'Medium' => 15..69,
    'Small'  => 1..14,
}

size_hash.find{|_, r| r === 40}[0]
# => "Medium"
于 2012-11-25T04:41:30.273 に答える
2

エッジケースを処理するさらに別のソリューション...

@size_hash = {
  'Large'  => 70..139,
  'Medium' => 15..69,
  'Small'  => 1..14,
}

some_value = @size_hash["Small"]
@min = some_value.first
@max = some_value.last
@size_hash.each_pair do |k, v|
    @min = [@min, v.first].min
    @max = [@max, v.last].max
end

puts "size_hash goes from #{@min} to #{@max}"

    # Given a number, return the name of the range which it belongs to.
def whichSize(p_number)
    @size_hash.each_pair do |k, v|
        return k if v.include?(p_number)
    end

    return "below minimum" if p_number < @min
    "above maximum" if p_number > @max
end

# test
[-10, 0, 1, 10, 14, 15, 20, 69, 70, 80, 139, 140, 1000].each do |e|
    puts "size of #{sprintf("%4s", e)} is #{whichSize(e)}"
end

$ ruby -w t.rb 
size_hash goes from 1 to 139
size of  -10 is below minimum
size of    0 is below minimum
size of    1 is Small
size of   10 is Small
size of   14 is Small
size of   15 is Medium
size of   20 is Medium
size of   69 is Medium
size of   70 is Large
size of   80 is Large
size of  139 is Large
size of  140 is above maximum
size of 1000 is above maximum
于 2012-11-25T14:21:19.230 に答える
1

範囲をキーとして保存した場合は、次のように実行できます。

size_hash = Hash.new {|hash, key| hash.find {|range,_| range.cover?(key) }.last }.merge({
  (1..14)   => 'Small',
  (15..69)  => 'Medium',
  (70..139) => 'Large'
})

これにより、ハッシュにデフォルトのprocが設定されるため、のような値を検索すると、size_hash[9]その値をカバーする最初の範囲が返されます。これは範囲外のエラーを処理しないことに注意してください。

于 2012-11-25T04:02:56.683 に答える