IT虾米网

Ruby 哈希插值

xiaohuochai 2024年01月13日 编程语言 214 0

我有一个混合类型的散列:

stuff = {:pack_one => ["blue_item", "red_item"], :pack_two => [:green_item, :purple_item, :yellow_item]} 

我需要将其转换成如下句子:

"pack_one contains a blue_item and red_item and pack_two contains a green_item, purple_item and yellow_item" 

所以我假设我需要使用 Enumerable 并迭代散列并构建句子,但我不确定如何做?

请您参考如下方法:

我的解决方案。符合要求比@Eureka 的回答更严格。

strings = stuff.map do |key, values| 
  "#{key} contains a #{values[0..-2] * ', '} and #{values.last}" 
end 
puts strings.join ' and ' 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!