-1

I want to add an attribute to my method from another class. I know how to work with attr_accessor but how does it work if the method has arguments?

class A
  attr_accessor :method # gives me wrong number of arguments
  attr_accessor :method(a,b,c) # gives me syntax error

  def method(a,b,c)
    print a
  end
end

a_class=A.new
a_class.method(5,3,2)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
shiney570
  • 9
  • 2
  • 1
    Do you know what `attr_acessor` does? Then just do that by yourself. If you don't know read [What is attr_accessor in Ruby?](https://stackoverflow.com/questions/4370960/what-is-attr-accessor-in-ruby). – cremno Jul 24 '15 at 23:11
  • 1
    Let's use the term "instance variable" rather than "attribute". When invoked on a class, [Module#attr_accessor](http://ruby-doc.org/core-2.0.0/Module.html#method-i-attr_accessor) creates getter and setter methods for a specified instance variable. If you write `class A; attr_accessor :a; end`, the methods `A#a` and `A#a=` are created. The first retrieves the value of the instance variable `@a`, the second sets the value (to the value of `a=`'s argument). There's no need to specify the number of arguments for these methods (and therefore you can't), as Ruby knows `a` has none and `a=` has one. – Cary Swoveland Jul 24 '15 at 23:32

1 Answers1

0

attr_accessor exists because it allows us to avoid declaring too many unnecessary reader and writer methods. Just remember: it's for reader and writer methods that either display an attribute or change its value respectively. That's literally what it means.

Therefore, if you wish to have a reader/writer method, or any other method with more than one parameter, since writer methods have one parameter, you need not put it as an attr_accessor, but simply write the method inside the class instead.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Charles
  • 1,384
  • 11
  • 18