Required Argument in initialize

wang xiao bo 's photo
wang xiao bo
·Sep 6, 2021·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

While calling the new method, we can pass the value hot. We can also tell Ruby that if no value is passed, then take hot as the default value.

class TeaMaker
   attr_reader :condition
   def initialize(condition = "hot")
      @condition = condition
   end

end

tea1 = TeaMaker.new
puts tea1.condition // hot

Now, when we are not providing any value, then hot becomes the default value. On the other hand, if we did provide a value, then that value would override the default value.

class TeaMaker
   attr_reader :condition
   def initialize(condition = "cold")
      @condition = condition
   end

end

tea1 = TeaMaker.new("hot")
puts tea1.condition // cold
 
Share this

Impressum

JavaScript Ruby on Rails