7

I want to use variable insite %w{} but this is generating only string.

I have try with

a="hello",
b="world"
%w{a b}

But this is display ["a", "b"] I want to display ["hello","world"]

3
  • Have you tried [a, b], because %w{all strings} creates a string array
    – lwe
    May 23, 2013 at 7:12
  • I know [a, b] will work but i want to use %w{all strings}
    – user2257812
    May 23, 2013 at 7:13
  • irb(main):017:0> %W(#{a} #{b}) => ["hello", "world"]
    – Anand Shah
    May 23, 2013 at 7:17

1 Answer 1

18

If you want to use variables you can use interpolation and the %W variant

a = "hello"
b = "world"

pp %W{#{a} #{b} this is normal text} #=> ["hello", "world", "this", "is", "normal", "text"]
1
  • As of version 2.6, the result of %w{#{x}}, as well as any combination of quotes, extra text, parens instead of brackets, etc. that I can think of (where x = 'a b c') always results in ["\#{x}"]` for me. This may have worked back in 2013, but unless I'm missing something stupid (entirely possible), the interpolation syntax is now escaped and taken as a literal.
    – BobRodes
    Jan 14, 2019 at 17:04

Your Answer

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