Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Fruit
- attr_accessor :color, :type
- def initialize(color, type)
- @color=color ||= 'green'
- @type=type ||='pear'
- end
- end
- apple=Fruit.new(red, apple)
- class Fruit
- attr_accessor :color, :type
- def initialize(params = {})
- @color = params.fetch(:color, 'green')
- @type = params.fetch(:type, 'pear')
- end
- def to_s
- "#{color} #{type}"
- end
- end
- puts(Fruit.new) # prints: green apple
- puts(Fruit.new(:color => 'red', :type => 'grape')) # prints: red grape
- puts(Fruit.new(:type => 'pomegranate')) # prints: green pomegranate
- class Fruit
- # Now this is the only thing you have to touch when adding defaults or properties
- def set_defaults
- @color ||= 'green'
- @type ||= 'pear'
- end
- def initialize(params = {})
- params.each { |key,value| instance_variable_set("@#{key}", value) }
- set_defaults
- instance_variables.each {|var| self.class.send(:attr_accessor, var.to_s.delete('@'))}
- end
- def to_s
- instance_variables.inject("") {|vars, var| vars += "#{var}: #{instance_variable_get(var)}; "}
- end
- end
- puts Fruit.new
- puts Fruit.new :color => 'red', :type => 'grape'
- puts Fruit.new :type => 'pomegranate'
- puts Fruit.new :cost => 20.21
- puts Fruit.new :foo => "bar"
- f = Fruit.new :potato => "salad"
- puts "f.cost.nil? #{f.cost.nil?}"
- @color: green; @type: pear;
- @color: red; @type: grape;
- @color: green; @type: pomegranate;
- @color: green; @type: pear; @cost: 20.21;
- @color: green; @type: pear; @foo: bar;
- f.cost.nil? true
- class Fruit
- attr_accessor :color, :type
- def initialize(args={})
- options = {:color => 'green', :type => 'pear'}.merge(args)
- self.color = options[:color]
- self.type = options[:type]
- end
- end
- apple = Fruit.new(:color => 'red', :type => 'apple')
- class Fruit
- attr_accessor :color, :type
- def initialize(color = 'green', type = 'pear')
- @color = color
- @type = type
- end
- def to_s
- "#{color} #{type}"
- end
- end
- puts Fruit.new # prints: green pear
- puts Fruit.new('red','apple') # prints: red apple
- puts Fruit.new(nil,'pomegranate') # prints: green pomegranate
- class Fruit
- attr_accessor :color, :type
- def initialize(args={})
- options = defaults.merge(args)
- @color = options.fetch(:color)
- @type = options.fetch(:type)
- end
- def defaults
- {
- color: 'green',
- type: 'pear'
- }
- end
- end
- apple = Fruit.new(:color => 'red', :type => 'apple')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement