Create array of symbols

前端 未结 3 1072
醉酒成梦
醉酒成梦 2021-01-30 03:22

Is there a cleaner way to do something like this?

%w[address city state postal country].map(&:to_sym) 
#=> [:address, :city, :state, :postal, :country]


        
相关标签:
3条回答
  • 2021-01-30 04:03

    With a risk of becoming too literal, I think the cleanest way to construct an array of symbols is using an array of symbols.

    fields = [:address, :city, :state, :postal, :country]
    

    Can't think of anything more concise than that.

    0 讨论(0)
  • 2021-01-30 04:11

    %i[ ] Non-interpolated Array of symbols, separated by whitespace (after Ruby 2.0)

    %I[ ] Interpolated Array of symbols, separated by whitespace (after Ruby 2.0)

    %i[address city state postal country]

    the cleanest way to do this is:

    %w[address city state postal country].map(&:to_sym)

    0 讨论(0)
  • 2021-01-30 04:25

    The original answer was written back in September '11, but, starting from Ruby 2.0, there is a shorter way to create an array of symbols! This literal:

    %i[address city state postal country]
    

    will do exactly what you want.

    0 讨论(0)
提交回复
热议问题