Skip to content

Instantly share code, notes, and snippets.

@NikitaAvvakumov
Last active November 25, 2015 11:47
Show Gist options
  • Save NikitaAvvakumov/38bd16152207365b6812 to your computer and use it in GitHub Desktop.
Save NikitaAvvakumov/38bd16152207365b6812 to your computer and use it in GitHub Desktop.
# Ruby's `=` can be a part of a method name, but is not a method on its own. Consider:
class MyClass
def initialize(value)
@a = value
end
def a=(new_value) # `=` is part of a method name
@a = new_value # `=` is an operator
end
def a; @a; end
end
temp = MyClass.new(7)
puts temp.a # => 7
temp.a = 9
puts temp.a # => 9
# Above, `temp.a = 9` is indeed a call to `temp`'s instance method `a=`.
# Thus, writing it as `temp.a= 9` is syntactically correct, if one is so inclined.
# This is why we can do the following
temp.send(:a=, 11)
puts temp.a # => 11
# However, lone `=` is not a method in Ruby, unlike e.g. `+`:
$ irb
:001> a = 7 # => 7
:002> a.send(:+, 2) # => 9
:003> a.send(:=, 11) # => SyntaxError, unexpected '='
:004> a.send('=', 11) # => NameError, undefined method `=` for 9:Fixnum
# Nor is `a=` a method call:
:005> send(:a=, 11) # => NoMethodError: undefined method `a=` for main:Object
:006> send('a=', 11) # => NoMethodError: undefined method `a=` for main:Object
# Which is why I can grudgingly accept the missing space in `instance.method= 99`, but not in `a= 99` :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment