在块内的上下文中访问整个哈希
Accessing entire hash in context inside block
假设我有这个哈希:
hash = { :c => "three", :a => "one", :b => "two" }
我想把这个放在最后:
one, two, three
现在说它很好地嵌套在不同的散列中。我想避免这样的事情:
puts "#{bigger_hash[0].hash[:a]}, #{bigger_hash[0].hash[:b]}, #{bigger_hash[0].hash[:c]}"
我知道 map
有这个表格,它让我可以在不定义顺序的情况下做这样的事情:
bigger_hash[0].hash.map{|k,v| v}.join(', ')
将输出:
three, one, two
这消除了灵活性。我想按照我想要的顺序明确解决这些问题(不一定是数字或字母!)
有没有一种方便的方法可以实现这一点?我在想一些事情:
bigger_hash[0].hash.magic{"#{a}, #{b} #{c}"}
# or
bigger_hash[9].hash.magic(:a, :b, :c).join(', ')
也许这就是你的答案:
bigger_hash[9].hash.values_at(:a, :b, :c).join(', ')
什么是 bigger_hash
returns?我不确定你在找什么,但据我所知,你想按 keys
和 return 对哈希进行排序,它是 values
。检查这个:
> hash = { :c => "three", :a => "one", :b => "two" }
> hash.sort.map{|e| e[1] }.join(' , ')
=> "one , two , three" # your expected output
或
> hash.values_at(:a, :b, :c).join(', ')
=> "one, two, three"
你也可以使用这种类型:
hash = { :c => "three", :a => "one", :b => "two" }
Hash[hash.sort].values.join(", ")
# => "one, two, three"
但地图方法在这种情况下更好。
首先要定义排序函数:
sorter = lambda { |o1, o2| o1 <=> o2 }
然后您就可以根据需要对值进行排序:
hash = { :c => "three", :a => "one", :b => "two" }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ one, two, three
例如对于相反的顺序,我们得到:
sorter = lambda { |o1, o2| o2 <=> o1 }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ three, two, one
传统红宝石没有 #to_h
方法:
hash.sort(&sorter).map(&:last).join(', ')
就地分拣机:
hash.sort(&lambda{ |o1,o2| o1 <=> o2 }).map(&:last).join(', ')
#⇒ "one, two, three"
希望对您有所帮助。
假设我有这个哈希:
hash = { :c => "three", :a => "one", :b => "two" }
我想把这个放在最后:
one, two, three
现在说它很好地嵌套在不同的散列中。我想避免这样的事情:
puts "#{bigger_hash[0].hash[:a]}, #{bigger_hash[0].hash[:b]}, #{bigger_hash[0].hash[:c]}"
我知道 map
有这个表格,它让我可以在不定义顺序的情况下做这样的事情:
bigger_hash[0].hash.map{|k,v| v}.join(', ')
将输出:
three, one, two
这消除了灵活性。我想按照我想要的顺序明确解决这些问题(不一定是数字或字母!)
有没有一种方便的方法可以实现这一点?我在想一些事情:
bigger_hash[0].hash.magic{"#{a}, #{b} #{c}"}
# or
bigger_hash[9].hash.magic(:a, :b, :c).join(', ')
也许这就是你的答案:
bigger_hash[9].hash.values_at(:a, :b, :c).join(', ')
什么是 bigger_hash
returns?我不确定你在找什么,但据我所知,你想按 keys
和 return 对哈希进行排序,它是 values
。检查这个:
> hash = { :c => "three", :a => "one", :b => "two" }
> hash.sort.map{|e| e[1] }.join(' , ')
=> "one , two , three" # your expected output
或
> hash.values_at(:a, :b, :c).join(', ')
=> "one, two, three"
你也可以使用这种类型:
hash = { :c => "three", :a => "one", :b => "two" }
Hash[hash.sort].values.join(", ")
# => "one, two, three"
但地图方法在这种情况下更好。
首先要定义排序函数:
sorter = lambda { |o1, o2| o1 <=> o2 }
然后您就可以根据需要对值进行排序:
hash = { :c => "three", :a => "one", :b => "two" }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ one, two, three
例如对于相反的顺序,我们得到:
sorter = lambda { |o1, o2| o2 <=> o1 }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ three, two, one
传统红宝石没有 #to_h
方法:
hash.sort(&sorter).map(&:last).join(', ')
就地分拣机:
hash.sort(&lambda{ |o1,o2| o1 <=> o2 }).map(&:last).join(', ')
#⇒ "one, two, three"
希望对您有所帮助。