text
stringlengths
0
444
name = "Bozhidar"
name = 'De\'Andre'
# good
name = 'Bozhidar'
name = "De'Andre"
----
==== Double Quote [[consistent-string-literals-double-quote]]
Prefer double-quotes unless your string literal contains " or escape characters you want to suppress.
[source,ruby]
----
# bad
name = 'Bozhidar'
sarcasm = "I \"like\" it."
# good
name = "Bozhidar"
sarcasm = 'I "like" it.'
----
=== No Character Literals [[no-character-literals]]
Don't use the character literal syntax `?x`.
Since Ruby 1.9 it's basically redundant - `?x` would be interpreted as `'x'` (a string with a single character in it).
[source,ruby]
----
# bad
char = ?c
# good
char = 'c'
----
=== Curlies Interpolate [[curlies-interpolate]]
Don't leave out `{}` around instance and global variables being interpolated into a string.
[source,ruby]
----
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}"
----
=== No `to_s` [[no-to-s]]
Don't use `Object#to_s` on interpolated objects.
It's called on them automatically.
[source,ruby]
----
# bad
message = "This is the #{result.to_s}."
# good
message = "This is the #{result}."
----
=== String Concatenation [[concat-strings]]
Avoid using `String#+` when you need to construct large data chunks.
Instead, use `String#<<`.
Concatenation mutates the string instance in-place and is always faster than `String#+`, which creates a bunch of new string objects.
[source,ruby]
----
# bad
html = ''
html += '<h1>Page title</h1>'