0

I've got array like this :

a = [27624,
     22,
     33,
     "ema",
     "test",
     11,
     nil]

When I do a.join(',') I get one bing string with values joined. How can I get the same effect but only for my strings to retain their type. Output should look like this :

"27624, 22, 33, 'ema', 'test', 11"
Gandalf StormCrow
  • 25,788
  • 70
  • 174
  • 263

1 Answers1

5
a.map{|e| e.is_a?(String) ? "'#{e}'" : e}.join(',')

Alternatively: (this may not always have the desired effect - particularly for nil, as well as some other types you haven't included here)

a.map(&:inspect).join(',')
PinnyM
  • 35,165
  • 3
  • 73
  • 81
  • yes that second part totally worked and looks elegant. Can you elaborate on the `a.map(&:inspect)` part. I mean I know about .map{|block| block} but what about `&:inspect`, what is that. Is there a link where I can read about it? – Gandalf StormCrow Jul 17 '13 at 14:13
  • @GandalfStormCrow ['What does map(&:name) mean in Ruby?'](http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby) – Charles Caldwell Jul 17 '13 at 14:32
  • 1
    I think you need compact before join. – sawa Jul 17 '13 at 14:56