18

To create an array with empty strings ['a', '', 'b', '', 'c'] (not one space strings ' '), using %W I can use %W[a #{} b #{} c], also I can concatenate arrays, but is it possible to create array with empty strings using just %w[]?

3
  • 6
    no. %w[] has no way to represent zero-length string as an element.
    – dbenhur
    Commented Oct 19, 2012 at 22:29
  • See also stackoverflow.com/questions/4064062/… (there the results contain a space - so it is a similar situation, not the same)
    – knut
    Commented Oct 23, 2012 at 20:58
  • @knut: I know about escaping space, but that is not what I want
    – tig
    Commented Oct 24, 2012 at 14:09

3 Answers 3

20

A couple of options

%W[a b c #{''} z]

%W[a b c] << " "

(I know this isn't using the %w{} syntax, but for good measure:

'a,b,c,,z'.split(',')

1
  • the first option given here is the best IMO. should be marked the correct answer
    – sixty4bit
    Commented Dec 5, 2014 at 16:28
3

You can use

 %w[a \   b \  c].map(&:strip)

,but I think it's not very clean.

-1

try using %W instead of %w and use \s escape character for the empty string

 %W[a \s b ]
4
  • 1
    %W[a \s b ] gives ['a', ' ', 'b'] instead of ['a', '', 'b']
    – tig
    Commented Mar 11, 2014 at 20:07
  • u can use %W[a #{""} b ] or %W[a #{String.new} b ] or %W[a #{} b], but i couldn't find any way you can get a empty string using %w
    – RubyMiner
    Commented Mar 12, 2014 at 7:13
  • this might help. %w[a b].insert(1, nil.to_s)
    – RubyMiner
    Commented Mar 12, 2014 at 7:39
  • use the first suggestion in professormeowingtons's answer above
    – sixty4bit
    Commented Dec 5, 2014 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.