Tips about Ruby string


1,使用迭代器和join的不同

  1. data=['1','2','3']
  2. s=''
  3. data.each{|x| s<<x<<' and '}
  4. puts s
  5. puts data.join(" and ")

line 4输出的是:1 and 2 and 3 and
line 5则是:1 and 2 and 3

可以使用each_with_index实现join
data.each_with_index{|x,i| ss<<x;ss<<' and ' if i<data.length-1}

2,<< pk +
使用前者向string中append时会比后者的性能有所提高,因为后者会创建新的string对象。

3,1)#{}中定义的变量或者类可以在#{}之外使用
      puts "Here is #{
        class Bar
            def bar
                " some text"
            end
        end
        Bar.new.bar}"
    bar=Bar.new
    puts bar.bar
输出:Here is some text
             some text
    2)避免#{}的转义作用
    foo="foo"
    puts "\##{foo}"
    puts '#{foo}'
    puts '\#{foo}'
    puts "#{foo}"
    puts "\#"
    3)使用END
    name = "Mr. Lorum"
    email = <<END
    Dear #{name},
        Unfortunately we cannot process your insurance claim at this
    time. This is because we are a bakery, not an insurance company.
    Signed,Nil, Null, and None

        Bakers to Her Majesty the Singleton
    END
    puts email

 

biaoflying

文献:http://www.verydemo.com/demo_c119_i3953.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值