Ruby:有没有更优雅的方式来做这个循环&阵列?

时间:2010-07-29 21:39:52

标签: ruby

好的,这段代码给了我我想要的东西,但似乎它可以更干净,所以这里是代码:

colour = ["red", "white", "orange", "black"]  
x=[]  
colour.each_with_index do |c, i|  
   x[i] = "<a href='http://#{c}.test.com'>#{c}</a>"  
end  
tags2 = x.join(", ")  
p "The code ==>#{tags2}<=== " 

任何参赛者?

2 个答案:

答案 0 :(得分:4)

tags2 = colour.map {|c| "<a href='http://#{c}.test.com'>#{c}</a>" }.join(", ")

map只为数组中的每个元素调用一个块,然后返回结果数组。

答案 1 :(得分:1)

tags = ["red", "white", "orange", "black"].map do |color|
    "<a href='http://#{color}.test.com'>#{color}</a>"
end.join(", ")
p "The code ==>#{tags}<==="