ruby - Creating a method that functions as both a class and instance method -
let's had class , wanted able call same method on class and instance of class:
class foo   def self.bar     puts 'hey worked'   end end   this lets me following:
foo.bar #=> hey worked   but want able do:
foo.new.bar #=> nomethoderror: undefined method `bar' #<foo:0x007fca00945120>   so modify class have instance method bar:
class foo   def bar     puts 'hey worked'   end end   and can call bar on both class , instance of class:
foo.bar #=> hey worked foo.new.bar #=> hey worked   now class foo 'wet':
class foo   def self.bar     puts 'hey worked'   end    def bar     puts 'hey worked'   end end   is there way avoid redundancy?
have 1 method call other. otherwise, no, there no way avoid "redundancy", because there is no redundancy. there 2 separate methods happen have same name.
class foo   def self.bar     puts 'hey worked'   end    def bar     foo.bar   end end      
Comments
Post a Comment