美文网首页
Ruby 里的 %Q, %q, %W, %w, %x, %r,

Ruby 里的 %Q, %q, %W, %w, %x, %r,

作者: YongpingZhao | 来源:发表于2016-10-10 10:07 被阅读0次

    %Q

    用于替代双引号的字符串. 当你需要在字符串里放入很多引号时候, 可以直接用下面方法而不需要在引号前逐个添加反斜杠 (")

    2.3.0 :015 > %Q(rudy said, "i'm not ruby")
     => "rudy said, \"i'm not ruby\""
    

    (...)也可用其他非数字字母的符号或成对的符号代替, 诸如#...#,!...!, +...+,{...},[...], <...>,/.../等.

    2.3.0 :016 > %Q/rudy said, "i'm not ruby"/
     => "rudy said, \"i'm not ruby\""
    2.3.0 :017 > %Q#rudy said, "i'm not ruby"#
     => "rudy said, \"i'm not ruby\""
    2.3.0 :018 > %Q!rudy said, "i'm not ruby"!
     => "rudy said, \"i'm not ruby\""
    

    %q

    与%Q类似,用于代替单引号的字符串

    2.3.0 :031 > what_ruby = 'this is ruby'
     => "this is ruby"
    2.3.0 :032 > %Q!rudy said, "#{what_ruby}"!
     => "rudy said, \"this is ruby\""
    2.3.0 :033 > %q!rudy said, "#{what_ruby}"!
     => "rudy said, \"\#{what_ruby}\""
    

    (...)也可用其他非数字字母的符号或成对的符号代替, 诸如#...#,!...!, +...+,{...},[...], <...>,/.../等.

    %W,%w

    %W语法近似于%Q, 用于表示其中元素被双引号括起的数组.
    %w语法近似于%q, 用于表示其中元素被单引号括起的数组.

    2.3.0 :031 > what_ruby = 'this is ruby'
     => "this is ruby"
    2.3.0 :034 > %W(hello,kitty,cat,dog,what_ruby)
     => ["hello,kitty,cat,dog,what_ruby"]          ###不能用逗号隔开,只能用空格
    2.3.0 :035 > %W(hello kitty cat dog what_ruby)
     => ["hello", "kitty", "cat", "dog", "what_ruby"]
    2.3.0 :036 > %W(hello kitty cat dog #{what_ruby})
     => ["hello", "kitty", "cat", "dog", "this is ruby"]###双引号中可以被解析
    2.3.0 :037 > %w(hello kitty cat dog #{what_ruby})
     => ["hello", "kitty", "cat", "dog", "\#{what_ruby}"]###单引号中不能被解析,被转义了。
    

    %x

    用于执行一段shell脚本,并返回输出内容。

    2.3.0 :038 > %x(route -n)
     => "Kernel IP routing table\nDestination     Gateway         Genmask         Flags Metric Ref    Use Iface\n0.0.0.0         10.6.0.1        0.0.0.0         UG    100    0        0 eth0\n10.6.0.0        0.0.0.0         255.255.252.0   U     0      0        0 eth0\n"
    2.3.0 :039 > %x(echo "hello world")
     => "hello world\n"
    

    %r

    语法近似于%Q, 用于正则表达式.

    2.3.0 :031 > what_ruby = 'this is ruby'
     => "this is ruby"
    2.3.0 :041 > %r(/home/#{what_ruby})
     => /\/home\/this is ruby/
    

    %s

    用于表示symbol, 但是不会对其中表达式等内容进行转化

    2.3.0 :031 > what_ruby = 'this is ruby'
     => "this is ruby"
    2.3.0 :042 > %s(a b c)
     => :"a b c"
    2.3.0 :043 > %s(abc)
     => :abc
    2.3.0 :044 > %s(what_ruby)
     => :what_ruby
    2.3.0 :045 > %s(#{what_ruby})
     => :"\#{what_ruby}"
    

    %i

    Ruby 2.0 之后引入的语法, 用于生成一个symbol数组

    2.3.0 :031 > what_ruby = 'this is ruby'
     => "this is ruby"
    2.3.0 :046 > %i(a b c)
     => [:a, :b, :c]
    2.3.0 :047 > %i(a b c #{what_ruby})
     => [:a, :b, :c, :"\#{what_ruby}"]
    

    相关文章

      网友评论

          本文标题:Ruby 里的 %Q, %q, %W, %w, %x, %r,

          本文链接:https://www.haomeiwen.com/subject/iwbmyttx.html