为了账号安全,请及时绑定邮箱和手机立即绑定

Tips about Ruby string

标签:
Ruby


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

data=['1','2','3']

s=''

data.each{|x| s<<x<<' and '}

puts s

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,You want to create a string that contains a representation of a Ruby variable or expression.

eg:   number=5

       puts "the number is #{number}"

       puts "the number is #{5}"

       puts "the number now is #{number-1}"

       puts "the number is #{number.next} or #{number.prior}"

       没有Fixnum#prior方法。

Discussion 

      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

另外END可以用任意的字符替代。

    hello=<<ok

        Does it ok?

    ok

    puts hello

这里有一个问题就是END前面不能有空格?

    

©著作权归作者所有:来自51CTO博客作者abio的原创作品,如需转载,请注明出处,否则将追究法律责任

职场cookbook休闲Ruby


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消