Rails 遍历数组内对象的属性,有什么好的方法?

secondrocker · October 27, 2012 · Last by small_fish__ replied at November 02, 2012 · 7223 hits

tagnames=[] list.tags.each{|t| tagnames.push(t.name) }
tagnames.join(',')

我是这么做的,看着真不舒服... 有什么更简便的,牛 X 的方法木有?

list.tags.reduce([]) { |arr, t| arr << t.name }.join(',')

list.tags.map{ |t| t.name }.join(',')

list.tags.map(&:name).join(',')

list.tags.collect{|t| t.name}.join(',')

#3 楼 @vincent 这是什么用法?

#5 楼 @simlegate map 接收一个块参数 &:attribute 相当于{|item| item.attribute}

select map reduce

You need to Sign in before reply, if you don't have an account, please Sign up first.