Ruby中的%表示法

后端开发   发布日期:2025年07月06日   浏览次数:123

     %{String}  用于创建一个使用双引号括起来的字符串,这个表示法与%Q{String}完全一样

  1. result = %{hello}
  2. puts "result is: #{result}, Type is:#{result.class}"
  3. #>>result is: hello, Type is:String

 

    %Q{String} 用于创建一个使用双引号括起来的字符串 

    %q{String} 用于创建一个使用单引号括起来的字符串 

 从说明中可以看出这两个表示法的区别就是一个使用双引号,一个使用单引号。使用双引号的字符串会对字符串中的变量做较多替换,而单引号则做较少的替换。

  1. world = "world"
  2. result = %Q{hello #{world}}
  3. puts "result is: #{result}, Type is:#{result.class}"
  4. #>>result is: hello world, Type is:String
  5. world = "world"
  6. result = %q{hello #{world}}
  7. puts "result is: #{result}, Type is:#{result.class}"
  8. #>>result is: hello #{world}, Type is:String

 

    %r{String} 用于创建一个正则表达式字面值 

  1. result = %r{world}
  2. puts result =~ "hello world"
  3. puts "result is: #{result}, Type is:#{result.class}"
  4. #>>6
  5. #>>result is: (?-mix:world), Type is:Regexp

 

    %w{String} 用于将一个字符串以空白字符切分成一个字符串数组,进行较少替换 
    %W{String} 用于将一个字符串以空白字符切分成一个字符串数组,进行较多替换 

  1. result = %w{hello world}
  2. puts "result is: #{result}, Type is:#{result.class}, length is:#{result.length}"
  3. #>>result is: helloworld, Type is:Array, length is:2

 

    %s{String} 用于生成一个符号对象 

  1. result = %s{hello world}
  2. puts "result is: #{result}, Type is:#{result.class}"
  3. sym = :"hello world"
  4. puts "the two symbol is the same: #{sym == result}"
  5. #>>result is: hello world, Type is:Symbol
  6. #>>the two symbol is the same: true

 

    %x{String} 用于执行String所代表的命令 

    比如: %x{notepad.exe}可以启动windows下的记事本

    PS:上面几个%表示法中用{}扩住了String,其实这个{}只是一种分割符,可以换成别的字符,比如(),那么%表示法就是%(String),当然还可以是别的字符,对于非括号类型的分割符,左右两边要相同,如%!String! 

以上就是Ruby中的%表示法的详细内容,更多关于Ruby中的%表示法的资料请关注九品源码其它相关文章!