Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does a ruby method ending with an "=" mean?

Tags:

ruby

What does a ruby method ending with an "=" mean?

See the available methods in this print out:

 2.2.0 :066 > obj.methods(false)
 => [:label=, :label, :description=, :description, :thumbnail=, :thumbnail, :attribution=, :attribution, :license=, :license, :logo=, :logo, :see_also=, :seeAlso=, :see_also, :seeAlso, :related=, :related, :within=, :within, :metadata=, :metadata, :sequences=, :sequences, :structures=, :structures, :viewing_hint=, :viewingHint=, :viewing_hint, :viewingHint, :viewing_direction=, :viewingDirection=, :viewing_direction, :viewingDirection, :service=, :service] 

For example whats this difference between label= and label?

like image 1000
Jeff Avatar asked Dec 02 '22 17:12

Jeff


1 Answers

foo= is no different than any other method, except:

  • it requires precisely one argument and
  • Ruby permits you to add spaces before the = character.

class Foo
  def foo=(other)
    puts 'hi'
  end
end
Foo.new.foo                 = 7
hi

class Goo
  def goo=
    puts 'hi'
  end
end
Goo.new.goo=

Ruby says, "I'm waiting for an argument...". So we provide one:

4

and then she complains about what she asked you to do:

#=> ArgumentError: wrong number of arguments (1 for 0)

= methods are typically used to create a setter for an instance variable (if attr_acccessor or attr_writer is not used):

class Foo
  def initialize(foo)
    @foo=foo
  end
  # getter
  def foo
    @foo
  end
  # setter
  def foo=(other)
    @foo = other
  end
end

f = Foo.new('dog')
f.foo
  #=> "dog" 
f.foo = 'cat'
  #=> "cat" 
f.foo
  #=> "cat" 
like image 78
Cary Swoveland Avatar answered Jan 05 '23 14:01

Cary Swoveland