Reputation:
The following code produces the output "xyz"
a = %w{x y z}
print a.to_s
Is there an option that can be added to the block to allow spaces to be added?
For example, I thought that by changing the code to this I might be able to space-separate the elements to produce an output of "x y z"
a = %w{"x " "y " "z "}
print a.to_s
Instead it produces this:
"x""y""z"
Upvotes: 6
Views: 1812
Reputation: 7195
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
Upvotes: 0
Reputation: 107728
a = ["xyz"].split("").join(" ")
or
a = ["x","y","z"].join(" ")
or
a = %w(x y z).join(" ")
Upvotes: 2
Reputation: 72936
You can include spaces by backslash-escaping them (then adding an additional space as a separator).
a = %w{x\ y\ z\ }
This can become hard to read though. If you want to put explicit quotation marks in there, you don't need %w{}
, just use a normal comma-delimited array with []
.
Upvotes: 6
Reputation: 19249
Don't use %w
for this--it's a shortcut for when you want to split an array from words. Otherwise, use the standard array notation:
a = ["x ", "y ", "z "]
Upvotes: 3