字符串 (Strings)
尽量使用字符串插值,而不是字符串拼接[link]
# 错误email_with_name = user.name + ' <' + user.email + '>'# 正确email_with_name = "# {user.name} <# {user.email}>"
另外,记住 Ruby 1.9 风格的字符串插值。比如说你要构造出缓存的 key 名:
CACHE_KEY = '_store'cache.write(@user.id + CACHE_KEY)
那么建议用字符串插值而不是字符串拼接:
CACHE_KEY = '%d_store'cache.write(CACHE_KEY % @user.id)
在需要构建大数据块时,避免使用
String# +。
而是用String# <<. 它可以原位拼接字符串而且它总是快于String# +,
这种用加号的语法会创建一堆新的字符串对象.[link]# 正确而且快html = ''html << '<h1>Page title</h1>'paragraphs.each do |paragraph|html << "<p># {paragraph}</p>"end
对于多行字符串, 在行末使用
\,而不是+
或者<<
[link]# 错误"Some string is really long and " +"spans multiple lines.""Some string is really long and " <<"spans multiple lines."# 正确"Some string is really long and " \"spans multiple lines."
