开发者

Ruby: Is there a more elegant way of doing this loop & array?

Okay, this code gives me exactly what I want but it seems that it could be cleaner, so here is the code:

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.开发者_JS百科join(", ")  
p "The code ==>#{tags2}<=== " 

Any takers?


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

map just calls a block for every element in the array, then returns the result array.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜