2012-11-12 328 views
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" 

所以我想我需要使用可枚舉和迭代散列和構建句子,但我不知道如何?

+0

你在語法上的正確性如何? –

回答

0

這裏是一個解決方案,使用Enumerable#mapArray#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" 

編輯:現在符合您的要求完美。

6

我的解決方案。符合要求比@Eureka答案更嚴格一些。

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

確實聰明和矮(我沒有想到這種方式擺脫三元運算符):) – Eureka

+1

不知道這種使用陣列#*; Array#join肯定比較習慣,但是我很欣賞這是多麼的簡潔! –

+0

連接似乎沒有爲散列定義。 –

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" 
+0

+1這就是我的想法。 –