What is the %w “thing” in ruby?

前端 未结 4 1402
闹比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 16:57

    • What is the proper name of that %w "thing"? Operator? Literal? Constructor?

    Not actually sure, string encoded literals I guess.

    • Does it matter whether I use {}s instead of []s?

    Nope. You can use almost any character actually. If you start with a {, [ or ( you need to close with the closing counterpart of that character, but other characters are closed with the same character. You probably want to use a character that is not going to appear inside your literal.

    %w_ foo bar _
    
    • Are there any other things like this (for example, one that gives you an array of symbols instead)?

    Not one for an array of symbols, but there is a %q for a single quoted string, %Q for a double quoted string, %r for a regex, and probably a few other as well I am forgetting.

    • Can they be "nested" (one %w inside another %w, in order to create nested arrays)?

    Nope. They are for quick and easy ways to create simple objects. If you need nesting, you need to use the more verbose syntax.

提交回复
热议问题