ruby · level 3 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
calls a method whose name is only data.
is code that works with code: calling, creating or catching methods while the program runs. The first tool is . order.send(:total) does the same as order.total, but the method name is a symbol or string you can keep in a variable, read from a file or build from text.
send can even call private methods, which is rarely what you want. public_send refuses, so professionals prefer it for names that come from outside. Before calling, asks whether the object has that method at all, so one bad name in the data does not crash the whole report.
class Order
attr_accessor :total, :status
end
order = Order.new
order.total = 42
order.status = "packed"
["total", "status", "colour"].each do |column|
if order.respond_to?(column)
puts "#{column}: #{order.public_send(column)}"
else
puts "#{column}: no such column"
end
end Never pass a name typed by a stranger straight to send, because it could call almost anything.
guess first
Setters and even + are methods. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Lamp
attr_accessor :colour
end
lamp = Lamp.new
lamp.public_send("colour=", "teal")
puts lamp.colour
puts 5.public_send(:+, 3)
p [3, 1, 2].public_send(:sort)
your turn
Your turn. Let the reader choose how the report is sorted.
Type name or age in the blank. The report sorts the pets by whichever method you named.
fix it
The settings never reach the profile. Fix the call.
- The error says
namewas given 1 argument but wants 0. Which method did you mean to call? namereads the value. The method that sets it is calledname=, with an equals sign.- On line 7, call
profile.public_send("#{field}=", value), then press run.
nailed it
you called methods by name. :D
public_send(:name)calls a method whose name is data.- Check
respond_to?before calling a name from outside. - Setters end in
=, likecolour=.
new words in your collection
- metaprogramming
- send
- public_send
- respond_to?
This lesson isn’t saved. A free account remembers every lesson you finish.