Ruby中的字符串編寫示例
優(yōu)先使用 字符串插值 來代替 字符串串聯(lián)。
# bad email_with_name = user.name + ' <' + user.email + '>' # good email_with_name = "#{user.name} <#{user.email}>" # good email_with_name = format('%s <%s>', user.name, user.email)
Consider padding string interpolation code with space. It more clearly sets the
code apart from the string.考慮使用空格填充字符串插值。它更明確了除字符串的插值來源。
"#{ user.last_name }, #{ user.first_name }"
Consider padding string interpolation code with space. It more clearly sets the
code apart from the string.
考慮替字符串插值留白。這使插值在字符串里看起來更清楚。
"#{ user.last_name }, #{ user.first_name }"
采用一致的字符串字面量引用風(fēng)格。這里有在社區(qū)里面受歡迎的兩種風(fēng)格,它們都被認(rèn)為非常好 -
默認(rèn)使用單引號(hào)(選項(xiàng) A)以及雙引號(hào)風(fēng)格(選項(xiàng) B)。
(Option A) 當(dāng)你不需要字符串插值或者例如 \t, \n, ' 這樣的特殊符號(hào)的
時(shí)候優(yōu)先使用單引號(hào)引用。
# bad name = "Bozhidar" # good name = 'Bozhidar'
(Option B) Prefer double-quotes unless your string literal
contains " or escape characters you want to suppress.
除非你的字符串字面量包含 " 或者你需要抑制轉(zhuǎn)義字符(escape characters)
優(yōu)先使用雙引號(hào)引用。
# bad name = 'Bozhidar' # good name = "Bozhidar"
第二種風(fēng)格可以說在 Ruby 社區(qū)更受歡迎些。該指南的字符串字面量,無(wú)論如何,
與第一種風(fēng)格對(duì)齊。
不要使用 ?x 符號(hào)字面量語(yǔ)法。從 Ruby 1.9 開始基本上它是多余的,?x 將會(huì)被解釋為 x (只包括一個(gè)字符的字符串)。
# bad char = ?c # good char = 'c'
別忘了使用 {} 來圍繞被插入字符串的實(shí)例與全局變量。
class Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end # bad - valid, but awkward def to_s "#@first_name #@last_name" end # good def to_s "#{@first_name} #{@last_name}" end end $global = 0 # bad puts "$global = #$global" # good puts "$global = #{$global}"
在對(duì)象插值的時(shí)候不要使用 Object#to_s,它將會(huì)被自動(dòng)調(diào)用。
# bad message = "This is the #{result.to_s}." # good message = "This is the #{result}."
操作較大的字符串時(shí), 避免使用 String#+ 做為替代使用 String#<<。就地級(jí)聯(lián)字符串塊總是比 String#+ 更快,它創(chuàng)建了多個(gè)字符串對(duì)象。
# good and also fast html = '' html << '<h1>Page title</h1>' paragraphs.each do |paragraph| html << "<p>#{paragraph}</p>" end
When using heredocs for multi-line strings keep in mind the fact
that they preserve leading whitespace. It's a good practice to
employ some margin based on which to trim the excessive whitespace.
heredocs 中的多行文字會(huì)保留前綴空白。因此做好如何縮進(jìn)的規(guī)劃。這是一個(gè)很好的
做法,采用一定的邊幅在此基礎(chǔ)上削減過多的空白。
code = <<-END.gsub(/^\s+\|/, '') |def test | some_method | other_method |end END #=> "def test\n some_method\n other_method\nend\n"
- 詳解Ruby中正則表達(dá)式對(duì)字符串的匹配和替換操作
- Ruby的字符串與數(shù)組求最大值的相關(guān)問題討論
- Ruby中操作字符串的一些基本方法
- Ruby中常用的字符串處理函數(shù)使用實(shí)例
- Ruby簡(jiǎn)潔學(xué)習(xí)筆記(一):字符串、數(shù)字、類和對(duì)象
- Ruby中創(chuàng)建字符串的一些技巧小結(jié)
- Ruby中實(shí)現(xiàn)把字符串轉(zhuǎn)換為類的2種方法
- Ruby中字符串左側(cè)補(bǔ)零方法實(shí)例
- Ruby字符串、條件、循環(huán)、數(shù)組、Hash、類基本操作筆記
- Ruby 字符串處理
- Ruby編寫HTML腳本替換小程序的實(shí)例分享
相關(guān)文章
ruby實(shí)現(xiàn)網(wǎng)頁(yè)圖片抓取
本文給大家分享的是個(gè)人使用ruby編寫的抓取網(wǎng)頁(yè)圖片的代碼,十分的簡(jiǎn)單實(shí)用,有需要的小伙伴可以參考下。2015-06-06