×

ruby · level 3 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.