2

我有一个混合类型的哈希:

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 并遍历哈希并构建句子,但我不确定如何?

4

3 回答 3

6

我的解决方案。适合要求比@Eureka 答案更严格一些。

strings = stuff.map do |key, values|
  "#{key} contains a #{values[0..-2] * ', '} and #{values.last}"
end
puts strings.join ' and '
于 2012-11-12T23:05:06.550 回答
3

如果您可以使用ActiveSupport,这是一个作弊:

require 'active_support/core_ext/array/conversions'
stuff.map{|k,v| "#{k} contains a #{v.to_sentence}"}.join(" and ")

结果:

1.9.3p125 > require 'active_support/core_ext/array/conversions'
 => true 
1.9.3p125 > stuff.map{|k,v| "#{k} contains a #{v.to_sentence}"}.join(" and ")
 => "pack_one contains a blue_item and red_item and pack_two contains a green_item, purple_item, and yellow_item" 

编辑:要摆脱牛津逗号,明确提供last_word_connector选项:

1.9.3p125 > stuff.map{|k,v| "#{k} contains a #{v.to_sentence(last_word_connector: " and ")}"}.join(" and ")
 => "pack_one contains a blue_item and red_item and pack_two contains a green_item, purple_item and yellow_item" 
于 2012-11-12T23:28:21.517 回答
0

这是一个解决方案,使用Enumerable#mapand Array#join

stuff.map do |k, v|
  "#{k} contains a #{v.size > 2 ? v[0..-2].join(", ") + " and " + v[-1].to_s : v.join(' and ')}"
end.join(" and ")
=> "pack_one contains a blue_item and red_item and pack_two contains green_item and purple_item and yellow_item"

编辑:现在完全符合您的要求。

于 2012-11-12T23:01:52.857 回答