开发者

How to compute 'map' in Ruby without using blocks?

开发者 https://www.devze.com 2023-04-03 06:55 出处:网络
I know I can do this in Ruby: [\'a\', \'b\'].map do |s| s.to_sym end and get this: [:a, :b] I\'m looking for a m开发者_如何学运维ore concise way to do it, without using a block. Unfortunately, t

I know I can do this in Ruby:

  ['a', 'b'].map do |s| s.to_sym end

and get this:

  [:a, :b]

I'm looking for a m开发者_如何学运维ore concise way to do it, without using a block. Unfortunately, this doesn't work:

  ['a', 'b'].map #to_sym

Can I do better than with the initial code?


Read a bit about Symbol#to_proc:

['a', 'b'].map(&:to_sym)
# or
['a', 'b'].map &:to_sym
# Either will result in [:a, :b]

This works if you're using Ruby 1.8.7 or higher, or if you're using Rails - ActiveSupport will add this functionality for you.


['a', 'b'].map(&:to_sym) is shorter

0

精彩评论

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