使用%w时包含空格

时间:2009-02-12 22:53:26

标签: ruby string formatting

以下代码生成输出“xyz”

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

是否有可以添加到块中的选项以允许添加空格?

例如,我认为通过将代码更改为此,我可以将元素空格分隔以生成“x y z”的输出

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

相反,它产生了这个:

“X” “Y” “Z”

4 个答案:

答案 0 :(得分:6)

您可以通过反斜杠包含空格(然后添加一个额外的空格作为分隔符)。

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

但这可能变得难以阅读。如果你想在那里放置明确的引号,你不需要%w{},只需使用带有[]的普通逗号分隔数组。

答案 1 :(得分:3)

不要使用%w - 这是您想要从单词中拆分数组的快捷方式。否则,请使用标准数组表示法:

a = ["x ", "y ", "z "]

答案 2 :(得分:2)

a = ["xyz"].split("").join(" ")

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

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

答案 3 :(得分:0)

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