WARNING Setter methods don’t return what you might think. When you use the syntactic sugar that lets you make calls to = methods look like assignments, Ruby takes the assignment semantics seriously. Assignments (like x=1) evaluate to whatever’s on their right-hand side. Methods usually return the value of the last expression evaluated during execution. But = method calls behave like assignments: the value of the expression ticket.price = 63.00 is 63.00, even if the ticket= method returns the string “Ha ha!” The idea is to keep the semantics consistent. Under the hood, it’s a method call; but it looks like an assignment and behaves like an assignment with respect to its value as an expression.
Created
February 25, 2014 09:13
-
-
Save tamouse/9205492 to your computer and use it in GitHub Desktop.
demo assignment methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a | |
fine | |
mess | |
a | |
fine | |
mess | |
#<RubyAssignmentDemo:0x007f9e82936e08 @a_field=[["a", "fine", "mess"]]> | |
[["a", "fine", "mess"]] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RubyAssignmentDemo | |
attr_accessor :a_field | |
def to_s | |
@a_field.to_s | |
end | |
def a_field=(*args) | |
@a_field = args | |
"HA HA" | |
end | |
end | |
demo = RubyAssignmentDemo.new | |
puts demo.a_field = %w{a fine mess} | |
puts demo.a_field | |
puts demo.inspect | |
puts demo.to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment