Including spaces when using% w

The following code outputs the output of "xyz"

a = %w{x y z} 
print a.to_s

Is there an option that can be added to a block to add spaces?

For example, I thought that by changing the code to this, I could use a space - separate the elements to output the output of "xy z"

a = %w{"x " "y " "z "}
print a.to_s

Instead, it produces this:

"x", "y", "g"

+5
source share
4 answers
a = ["xyz"].split("").join(" ")

or

a = ["x","y","z"].join(" ")

or

a = %w(x y z).join(" ")
+2
source

You can include spaces using backslash escaping (then adding extra space as a delimiter).

a = %w{x\  y\  z\ }

. , %w{}, - [].

+5

Do not use %wfor this - this is a shortcut for when you want to split an array into words. Otherwise, use the standard array entry:

a = ["x ", "y ", "z "]
+2
source
def explain
  puts "double quote equivalents"
  p "a b c", %Q{a b c}, %Q(a b c), %(a b c), %<a b c>, %!a b c! # & etc
  puts

  puts "single quote equivalents"
  p 'a b c', %q{a b c}, %q(a b c), %q<a b c>, %q!a b c! # & etc.
  puts

  puts "single-quote whitespace split equivalents"
  p %w{a b c}, 'a b c'.split, 'a b c'.split(" ")
  puts

  puts "double-quote whitespace split equivalents"
  p %W{a b c}, "a b c".split, "a b c".split(" ")
  puts
end

explain

def extra_credit
  puts "Extra Credit"
  puts

  test_class = Class.new do
    def inspect() 'inspect was called' end
    def to_s() 'to_s was called' end
  end

  puts "print"
  print test_class.new
  puts "(print calls to_s and doesn't add a newline)"
  puts

  puts "puts"
  puts test_class.new
  puts "(puts calls to_s and adds a newline)"
  puts

  puts "p"
  p test_class.new
  puts "(p calls inspect and adds a newline)"
  puts
end

extra_credit
0
source

All Articles