Skip to content

Instantly share code, notes, and snippets.

@halida
Created May 19, 2012 07:25
Show Gist options
  • Save halida/2729866 to your computer and use it in GitHub Desktop.
Save halida/2729866 to your computer and use it in GitHub Desktop.
ruby class machanism example 1
class Sth
def present
raise NotImplementedError
end
def log s
puts s
end
end
class Person < Sth
def eat sth
if self.can_eat > sth.size
log "#{self.present} is eating #{sth.present} with size #{sth.size},"
self.can_eat -= sth.size
log "#{self.represent} can eat more #{self.can_eat}"
else
log "#{self.present} is trying to eat #{sth.present} with size #{sth.size},"
log "but #{self.represent} cannot eat more."
end
end
def can_eat
@eat_size ||= (rand * 5 + 3).to_i
end
def can_eat= size
@eat_size = size
end
end
class Person
def initialize attrs
@attrs = attrs
@attrs[:gender] ||= :male
end
def represent
case @attrs[:gender]
when :male then "he"
when :female then "she"
else "it"
end
end
def present
@attrs[:name]
end
end
class Apple < Sth
attr_reader :size
def initialize
@size = (rand * 4 + 1).to_i
end
def present
"apple"
end
end
me = Person.new name: "halida"
apples = 12.times.map{Apple.new}
apples.each {|apple| me.eat apple}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment