Wednesday, April 6, 2011

including spaces while using %w

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"

From stackoverflow
  • 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 "]
    
  • 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 [].

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

    or

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

    or

    a = %w(x y z).join(" ")
    
    Chuck : The problem you had is that array.to_s in Ruby before 1.9 just stuck all the elements end-to-end. The problem was not in your array data, but the method that printed the array. That's why %w{x y z}.join(' ') works fine. Also, to include spaces in a %w array values, use "\ " (backslash-space).
  • 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 comments:

Post a Comment