• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ruby字符串学习笔记1

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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"

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
一步一步学Ruby(十一):控制语句发布时间:2022-07-14
下一篇:
用rbenv给整个系统安装ruby(所有用户都可用)发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap