Ruby calls .inspect on the return value of the expression. Inspect returns a string representation of the object. For strings this is the string enclosed in "", for numbers this is just the number. For arrays this is [first element, second, ...]. You can define your own .inspect:
Code ruby:
class Person
def initialize(first_name, last_name, sex)
@first_name = first_name
@last_name = last_name
@sex = sex
end
def title
case @sex
when :male: "Mr."
when :female: "Ms."
end
end
def inspect
"#{title} #{@first_name} #{@last_name}"
end
end
It works like this:
Code:
irb> Person.new("Joe", "Average", :male)
=> Mr. Joe Average
As you can see, the Ruby intepreter called .inspect and printed the result to the console.
Bookmarks