Went over this code on RubyMonk:
class Item
def initialize(item)
@item = item
end
def show
puts "The item name is: #{self}"
end
def to_s
"#{@item}"
end
end
Item.new("potion").show
The code passes but the use of the self variable is a bit ambiguous to me. You could've easily supplanted to_s with self in the show method and gotten the same results. Can somebody explain the difference between both interpolations and why/how self is used here? Additionally, without the the method to_s, the code returns a proxy. What is the significance of defining the to_s here?
String interpolation implicitly calls the to_s method on an object. So, when you define the to_s method on Item, you are explicitly telling that object how to represent itself with respect to a string. self is used in this case because there is an implicit call to to_s within the interpolation of the Item object. Defining to_s explicitly tells Item how to render itself within a string.
For some additional details, check out this excellent post on explicit vs. implicit conversion methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With