Skip to content

Instantly share code, notes, and snippets.

@tamouse
Created February 25, 2014 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamouse/9205492 to your computer and use it in GitHub Desktop.
Save tamouse/9205492 to your computer and use it in GitHub Desktop.
demo assignment methods

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.

a
fine
mess
a
fine
mess
#<RubyAssignmentDemo:0x007f9e82936e08 @a_field=[["a", "fine", "mess"]]>
[["a", "fine", "mess"]]
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