2016-07-15 57 views
-1
formatter = "%{first} %{second} %{third} %{fourth}" 

puts formatter % {first: 1, second: 2, third: 3, fourth: 4} 

puts formatter % {first: "one", second: "two", third: "three", fourth: "four"} 

puts formatter % {first: true, second: false, third: true, fourth: false} 

puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter} 

puts formatter % { 
    first: "I had this thing.", 
    second: "That you could type up right.", 
    third: "But it didn't sing.", 
    fourth: "So I said goodnight." 
} 

我很困惑你會在紅寶石中使用格式字符串,有人可以向我解釋。由於紅寶石格式字符串有什麼用途

+1

你的例子並沒有使用很多字符串格式的功能,特別是轉換和填充。請參閱[這裏](https://www.blackbytes.info/2012/01/ruby-string-formatting/)關於這個 –

+0

的教程這不是一個好問題。格式化字符串在Fortran早期的語言中非常常見,用於提供調整文本中列寬和列對齊的方法。 Ruby在提供它們時並不是孤立的,因此對「格式字符串」的搜索將返回描述它們及其值的多個鏈接。 「[問]」和鏈接頁面和http://meta.stackoverflow.com/q/261592/128421將幫助你。 –

回答

1

僞代碼:

MAIL_TEMPLATE = <<-TMPL 
Hello, %{name}! 

The support for %{product} will be ended at %{date} unless 
due to insufficient amount of money on your account %{account}. 

The amount to pay to continue using %{product}: %{debt} 
TMPL 

Storage.all_users.map(&:to_hash).each |user| 
    send_email(user.delete[:email], MAIL_TEMPLATE % user) if user[:debt] 
end 

以上可以用於發送電子郵件到對他們的帳戶的錢沒有足夠的用戶量。注意,除了電子郵件模板外,還有2LOC。

請參考@ mu-is-too-short下面的非常有價值的評論。

+0

重要的是,'MAIL_TEMPLATE'只是一個字符串,可以存儲在一個單獨的文件中(除非您想使用'eval'或類似的不愉快性,否則'#{}'內插不會發生這種情況)。 –