如果您可以使用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"
你在語法上的正確性如何? –