- ruby字符串对象使用单引号与多引号输出的区别
key:两者输出字符串时的处理的次数不一样
‘' 单引号原生输出 处理为 0
“” 双引号则对字符串中的特殊字符(转义)进行转义 例如 \n 等 还有#{….} 占位符需要使用””进行转义。
# Ruby的字符串对象生成有两种方式,字符串文字值加单引号或加双引号。
# 两种方式主要区别在于构造文字量时,对字符串的处理次数不同。
# 单引号时,Ruby对字符串值不做处理,里边是什么就是什么。
# 双引号时,Ruby首先要查找文本中要替换的字符,即带反斜杠的字符,用二进制替换。
# 最常见的就是\n;其次,这种方式下可以插入表达式#{...},那就要处理表达式,将其替换成具体的值。
# #{i}相当于占位符,需要 "" 双引号的支持
irb(main):001:0> puts 'hello world'
hello world
=> nil
irb(main):002:0> puts "hello world"
hello world
=> nil
irb(main):003:0> puts 'hello \nworld'
hello \nworld
=> nil
irb(main):004:0> puts "hello \nworld"
hello
world
=> nil
-----------------------------------------------------------------------------------------------------------------------------
irb(main):006:0> puts '#{a}’ #这里原生输出
#{a}
=> nil
irb(main):007:0> puts "#{a}” #这里的 #{a}作为转义 将变量a输出,但a未定义,所以报错
NameError: undefined local variable or method `a' for main:Object
from (irb):7
from /usr/bin/irb:12:in `<main>'
|
puts 与 p 、print的区别与共同点
puts | p(与引号抗衡) | ||
有无返回值 | n | y | n |
是否换行 | y | y | n |
是否识别“”双引号中的转义字符 | y | n | y |
# (1)puts会识别双引号內的转义符,并自动换行
# (2)print会识别双引号內的转义符,不自动换行
# (3)p不会识别双引号內的转义符,并自动换行
irb(main):014:0> puts 'hello \nworld'
hello \nworld
=> nil
irb(main):015:0> print 'hello \nworld'
hello \nworld=> nil
irb(main):016:0> p 'hello \nworld'
"hello \\nworld"
=> "hello \\nworld"
---------------------------------------------------------------------------------
irb(main):018:0> print "hello \nworld"
hello
world=> nil
irb(main):019:0> puts "hello \nworld"
hello
world
=> nil
irb(main):020:0> p "hello \nworld"
"hello \nworld"
=> "hello \nworld"
irb(main):021:0>
|