From: DrBenway Date: 2008-01-26T05:19:58+09:00 Subject: Re: to sleep no more On Jan 25, 8:27 pm, Stephen Kratzer wrote: > On Friday 25 January 2008 13:25:00 DrBenway wrote: > > > > > hi all, > > > I'm a ruby noop trying his first steps. I'd like a little advice. > > > What I want to make is the following. > > > An object Chicken > > - its attribute starts as 'egg' > > - after x times sleep() it the attribute gets the value chicken > > - x times sleep later the object can make a call to make a new > > instance of chicken (creating another egg) > > > I could make a method to change the attribute and call this from my > > main program. > > In other words my sleep method would be in my main program and call > > the objects method. > > I was wondering if it would be possible to keep the sleep in the > > object. > > (Since I was planning on creating some other animals as well, each > > with a special amount of time needed to go to the next step.) > > > I think it's called threads in ruby but I'm not sure. (if it's called > > threads is this the way to handle this problem? Does it act like an > > Ajax call?) > > > Many thnx > > > DrBenway > > Something like this might work for your purposes: > > class Animal > attr_reader :incubation_period, :maturation_period, :from_type, > :to_type, :current_type, :slept, :children > > def initialize(i_period = 60, m_period = 120, from = "egg", to > = "chicken") > @incubation_period = i_period > @maturation_period = m_period > @slept = 0 > @from_type = from > @to_type = to > @current_type = @from_type > @children = [] > end > > def mysleep(seconds = @incubation_period) > @slept += sleep(seconds) > if @slept >= @incubation_period > @current_type = @to_type > end > end > > def give_birth(count = 1) > if @slept >= @maturation_period > for number in children.length..(children.length + > count - 1) > puts "I had another child." > children[number] = > Animal.new(@incubation_period, @maturation_period, @from_type, @to_type); > end > else > puts "I'm too young to give birth." > end > end > end > > snake = Animal.new(5, 10, "egg", "snake") > snake.mysleep(4) > puts snake.current_type > snake.give_birth > snake.mysleep(4) > puts snake.current_type > snake.give_birth > snake.mysleep(4) > puts snake.current_type > snake.give_birth(5) Wow thnx Stephen for coocking up an example so fast :) That's indeed what I was planning to do. The only thing that may not have been very obvious (sorry for this) in my example above was: Is there a way to take the snake.mysleep(4) out of our main program and put it in the class/object itself That way I call snake = Animal.new(5, 10, "egg", "snake") once and from then on it leads a life on its own (that's what got me to think that I needed threads). Same goes for all the other snakes that get born from the first. I don't feel like messing with arrays of snakes,pigs,boars,chickens,... out of the classes