ruby 字串學習筆記1

c3tc3tc3t發表於2015-11-30

1 從一種資料結構中構件字串

hash = { key1: "val1", key2: "val2" }
string = ""
hash.each { |k,v| string << "#{k} is #{v}\n" }
puts string
# key1 is val1
# key2 is val2

變種

string = ""
hash.each { |k,v| string << k.to_s << " is " << v << "\n" }

更高效辦法使用 Array#join

puts hash.keys.join("\n") + "\n"
# key1
# key2

或者

puts hash.keys.join("") 

# key1key2

 2 建立一個包含ruby變數或者表示式的字串

number = 5
"The number is #{number}."# => "The number is 5."
"The number is #{5}."# => "The number is 5."
"The number after #{number} is #{number.next}."# => "The number after 5 is 6."
"The number prior to #{number} is #{number-1}."# => "The number prior to 5 is 4."
"We're ##{number}!"# => "We're #5!"

也可以這樣使用但不要這麼做

%{Here is #{class InstantClass
        def bar
          "some text"
        end
            end
       InstantClass.new.bar
 }.}
# => "Here is some text."

here document使用

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

# => "Dear Mr. Lorum,\nUnfortunately we cannot process your insurance claim at this\ntime. This is because we are a bakery, not an insurance company.\nSigned,\nNil, Null, and None\nBakers to Her Majesty the Singleton\n"
<<end_of_poem
There once was a man from Peru
Whose limericks stopped on line two
end_of_poem
# => "There once was a man from Peru\nWhose limericks stopped on line two\n"

 

相關文章