ruby基础系列-ruby字符串对象使用单引号与多引号输出的区别与共同点

  • 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(与引号抗衡) print
有无返回值 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>






















  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值