What is the %w “thing” in ruby?

前端 未结 4 1426
闹比i
闹比i 2020-12-28 16:41

I\'m referring to the %w operator/constructor/whatever you may call it, used like this:

%w{ foo bar baz }
=> [\"foo\", \"bar\", \"baz\"]

4条回答
  •  清歌不尽
    2020-12-28 17:02

    1) It is a litteral, where it is a % then a r(regular expression), w(array), q(string) etc to denote different litterals.

    2)

    ruby-1.9.2-p136 :001 > %w{1 2 3}
     => ["1", "2", "3"] 
    ruby-1.9.2-p136 :002 > %w[1 2 3]
     => ["1", "2", "3"] 
    
    ruby-1.9.2-p136 :008 > %w!a s d f!
     => ["a", "s", "d", "f"] 
    
    ruby-1.9.2-p136 :009 > %w@a s d f@
     => ["a", "s", "d", "f"] 
    

    So you can see that you can use any charater as long as it marks both the beginning and end of the content.

    3)

    Here are some other examples:

    Strings:(%q or %Q)

    ruby-1.9.2-p136 :016 > %Q[ruby is cool]
     => "ruby is cool" 
    ruby-1.9.2-p136 :017 > %q[ruby is "cool"]
     => "ruby is \"cool\"" 
    

    Regex: (%r)

    ruby-1.9.2-p136 :019 > %r[(\w+)]
     => /(\w+)/ 
    

    Sys command: (%x)

    ruby-1.9.2-p136 :020 > %x[date]
     => "Tue Mar 29 12:55:30 EDT 2011\n"
    

    4) They cannot be nested because the %w means white space divided array. So if you try to do multi level, it would look like this:

    ruby-1.9.2-p136 :003 > %w{1 %w{2 3 4} 5}
     => ["1", "%w{2", "3", "4}", "5"] 
    

    To accomplish this, you would need to use the more verbose syntax:

    ruby-1.9.2-p136 :011 > [1, [2,3,4], 5]
     => [1, [2, 3, 4], 5] 
    

提交回复
热议问题