亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

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下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消