如何只调用哈希中的键或值?

use*_*348 0 ruby ruby-on-rails

如何仅从哈希中调用键或值?在以下示例中,我如何获取要返回的代码

猫是懒惰的

狗很有趣

河马很大

任何的想法??

['cat' => 'lazy', 'dog' => 'fun', 'hippo' => 'big'].each do |animal|
    template = ERB.new "#{animal}'s are #{animal}"
    puts template.result(binding)
end
Run Code Online (Sandbox Code Playgroud)

Kir*_*rat 5

我建议你使用Hash而不是Array:

{'cat' => 'lazy', 'dog' => 'fun', 'hippo' => 'big'}.each do |animal, character|
    template = ERB.new "#{animal}'s are #{character}"
    puts template.result(binding)
end
Run Code Online (Sandbox Code Playgroud)

cat's are lazy
dog's are fun
hippo's are big
Run Code Online (Sandbox Code Playgroud)