Ruby 1.8のいくつかのシナリオ。ハッシュがある場合
# k is name, v is order
foo = { "Jim" => 1, "bar" => 1, "joe" => 2}
sorted_by_values = foo.sort {|a, b| a[1] <==> b[1]}
#sorted_by_values is an array of array, it's no longer a hash!
sorted_by_values.keys.join ','
私の回避策はto_hash
、Array クラスのメソッドを作成することです。
class Array
def to_hash(&block)
Hash[*self.collect { |k, v|
[k, v]
}.flatten]
end
end
その後、次のことができます。
sorted_by_values.to_hash.keys.join ','
これを行うより良い方法はありますか?