nil, true and symbols
Three small values turn up everywhere in Ruby. The first is nil – “nothing”. You get it whenever there is no answer: a hash key that doesn't exist, a position past the end of an array, a find that finds nothing:
animal = { name: "Chunky" }
p animal[:age]
p [1, 2, 3][10]
p [1, 2, 3].find { |n| n > 5 }
nil.classnil is a real object with methods of its own. nil? asks whether something is nil, and to_s, to_a and to_i turn it into an empty string, an empty array and 0:
p nil.nil?
p 42.nil?
p nil.to_s
p nil.to_a
nil.to_iIn an if only two values count as false: false and nil. Everything else counts as true – even 0, the empty string and the empty array, unlike in many other languages:
[false, nil, 0, "", [], "bacon"].each do |value|
if value
puts "#{value.inspect} counts as true"
else
puts "#{value.inspect} counts as false"
end
endTwo shortcuts deal with nil. a || b gives a fallback: it is a, unless a is nil or false – then it is b. And ||= assigns only when the variable is still empty, which is handy for “set it once”:
nickname = nil
puts nickname || "no nickname"
nickname ||= "Chunky"
nickname ||= "Kaz" # already set: stays "Chunky"
nicknameCalling a method on nil is the most common error there is: undefined method 'upcase' for nil. The safe navigation operator &. only calls the method when there is something there; otherwise the whole expression is simply nil – and || can catch it:
foods = { "Chunky" => "bacon", "Kaz" => "eggs" }
p foods["Chunky"]&.upcase
p foods["Isi"]&.upcase
foods["Isi"]&.upcase || "NOTHING"And symbols? :bacon looks like a string without quotes, and in a way it is one: a name. But a symbol exists only once – every :bacon in your program is the very same object, and it can never be changed. to_s and to_sym convert between the two:
p :bacon.equal?(:bacon) # the very same object, every time
p :bacon.frozen? # and it never changes
p :bacon.to_s
"bacon".to_symThat makes symbols the favourite keys of hashes: they are names, not text. But data from outside – a file, the web – comes with strings as keys. transform_keys(&:to_sym) turns them into symbols:
from_the_web = { "name" => "Kaz", "food" => "eggs" }
kaz = from_the_web.transform_keys(&:to_sym)
kaz[:food]A rule of thumb: text you show to people is a string, a name your program uses inside is a symbol. And wherever something might be nil, decide on purpose what should happen – with ||, with &. or with an if.
total – a dish the menu doesn't know counts 0 – and collect in missing the dishes that have no price.menu = { bacon: 4.5, egg: 1.2 }
order = ["bacon", "toast", "egg"]
# total = ... # the prices of the order; a dish without a price counts 0
# missing = ... # the dishes of the order that have no price
groups by their first letter: { "b" => ["bacon", "banana"], … }. The trick is ||=: for each word, make sure its letter has an empty array (if it doesn't have one yet), then add the word to it.words = %w[bacon egg banana eel apple]
groups = {}
# for every word: groups[its first letter] ||= [] and then add the word