天天看點

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,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前面不能有空格?

繼續閱讀