我正在处理一个类似这样的散列:

h = {
    "side1"=>["green", "Green"],
    "side2"=>["verde", "Verde"]
}

但是,它可能只有一个项目:
h = {
    "side2"=>["verde", "Verde"]
}

我想输出散列,使其看起来像这样:
用户将side1从绿色更改为绿色,side2从verde更改为verde
当有两个项目时,将从“和”分隔开。否则它将如下所示:
用户将side2从verde更改为verde
这一切都发生在我的rails视图脚本中。如何编写代码才能做到这一点?

最佳答案

你可以这样做:

h = {
    "side1"=>["green", "Green"],
    "side2"=>["verde", "Verde"]
}
h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.join(' and ')
# "side1 from green to Green and side2 from verde to Verde"

h = {
    "side2"=>["verde", "Verde"]
}
h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.join(' and ')
# side2 from verde to Verde"

因此,在erb看来:
User changed <%= h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.join(' and ') %>.

如果你经常做这类事情,那么你可能想为它建立一个助手。
您也可以使用to_sentence,因为您在rails中:
User changed <%= h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.to_sentence %>.

to_sentence方法也可以更好地扩展到两个以上的元素。所以,如果你也有"side3"=>["pancakes", "Pancakes"],那么你会得到:
User changed side1 from green to Green, side2 from verde to Verde, and side3 from pancakes  to Pancakes.

08-26 08:41