如果您可以使用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"