Search code examples
rubypage-object-gem

Difference between self.element = 'this' and self.send("element=", 'this')


I am trying to understand why these two things return different values.

Value is a string, and field is a text_field.

def populate_text(field, value)
  self.send "user_name=", value
end
# => nil

def populate_text(value)
  self.user_name = value
end
# => "value"

Why do self and send have different return values?

This class includes PageObject if that helps.


Solution

  • Ruby's syntax sugar for calling methods whose name ends with = always returns the righthand value, regardless of the return value of the method.

    This is not the case when you use send to invoke the method. For example:

    class Foo
      def bar=(n)
        :ohno
      end
    end
    
    f = Foo.new
    x = (f.bar = 42)
    y = f.send("bar=", 42)
    p [x,y]
    #=> [42, :ohno]
    

    So, you would get two different values if your user_name= method has a return value that is not the argument to the method.