In Ruby, why does nil[1]=1 evaluate to nil?

Some random findings: [only in Ruby 2.3.0p0] The method doesn’t seem to exist: nil.method(:[]=) #=> NameError: undefined method `[]=’ nil.respond_to?(:[]=) #=> false And you can’t invoke it using send: nil.send(:[]=) #=> NoMethodError: undefined method `[]=’ Ruby evaluates neither the right hand side, nor the argument, i.e. nil[foo]=bar doesn’t raise a NameError, although foo and bar … Read more

How can I intercept method call in ruby?

This is one way to do it: class Superclass def before_each_method name p [:before_method, name] end def self.method_added name return if @__last_methods_added && @__last_methods_added.include?(name) with = :”#{name}_with_before_each_method” without = :”#{name}_without_before_each_method” @__last_methods_added = [name, with, without] define_method with do |*args, &block| before_each_method name send without, *args, &block end alias_method without, name alias_method name, with @__last_methods_added = … Read more

Method and variable name is the same

The ambiguity between local variables and methods only arises for receiverless message sends with no argument list. So, the solution is obvious: either provide a receiver or an argument list: self.hello hello() See also How does ruby allow a method and a Class with the same name? Optional parens in Ruby for method with uppercase … Read more