A question on method name

Hello,

This works fine for me:

class Horse

  def name
          @name
  end

    def nameset(v1,v2)
            @name = v1 + v2.to_s
    end

end

xx=Horse.new
xx.nameset("hello ",1)
p xx.name

But if I changed the method name, it won’t work.

class Horse

  def name
          @name
  end

    def name=(v1,v2)
            @name = v1 + v2.to_s
    end

end

xx=Horse.new
xx.name=("hello ",1)
p xx.name

the error says:

syntax error, unexpected ‘,’, expecting ‘)’
xx.name=("hello ",1)
^

Please help, thanks in advance.

On 12.12.2009 08:27, Ruby N. wrote:

    end

syntax error, unexpected ‘,’, expecting ‘)’
xx.name=("hello ",1)
^

Please help, thanks in advance.

Methods with assignment operator are separately treated by the parser -
as you just learned. You can only have 1 argument.

Btw, usually an assignment method, does just that. In your case you are
concatenating two strings which is probably worth a different method
name.

Kind regards

robert

Ruby N. wrote:

Hello,

This works fine for me:

class Horse

  def name
          @name
  end

    def nameset(v1,v2)
            @name = v1 + v2.to_s
    end

end

xx=Horse.new
xx.nameset("hello ",1)
p xx.name

But if I changed the method name, it won’t work.

class Horse

  def name
          @name
  end

    def name=(v1,v2)
            @name = v1 + v2.to_s
    end

end

xx=Horse.new
xx.name=("hello ",1)
p xx.name

the error says:

syntax error, unexpected ‘,’, expecting ‘)’
xx.name=("hello ",1)
^

Please help, thanks in advance.

Hi,

class Foo

def bar
@bar
end

def bar= *args
@bar = args.join
end

end

x = Foo.new.bar= 1,2,3 # => [1,2,3]
x.bar # => “123”

  • Rob

x = Foo.new.bar= 1,2,3 # => [1,2,3]
x.bar # => “123”

Oops. If you want that to work as-is…
x = Foo.new
x.bar= 1,2,3 # => [1,2,3]
x.bar # => “123”

  • Rob