ruby 字符串学习笔记1

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"

 

转载于:https://www.cnblogs.com/or2-/p/5006902.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值