From: "Eric I." Date: 2008-06-07T22:33:50+09:00 Subject: Re: using portions of other methods in a new method On Jun 7, 9:10 am, Jason Lillywhite wrote: > How do you take a piece of a method and use it in another? Here is my > simple example: > > class MyArray >   def counter >     result = [] >     i = 0 >     a = 1 >     b = 0 >     while i <= 5 do >       a = a + 1 >       b = b +1.5 >       result << b.to_s + "\t" + a.to_s >       i += 1 >     end >     puts result >   end >   def counter2 >     counter >   end > end > > test = MyArray.new > puts test.counter2 > > I want counter2 method to take the array "b" and do something with it, > like this: > b.inject {|sum, element| sum+element} > I just can't figure out how to transfer b from one method to another. Is > there a clean way to do this? Hi Jason, If I understand you correctly, you want your counter method to return b to its caller. The method will return the value of the last expression evaluated, or alternatively you can use a return statement anywhere within the method. ==== class MyArray def counter result = [] i = 0 a = 1 b = 0 while i <= 5 do a = a + 1 b = b +1.5 result << b.to_s + "\t" + a.to_s i += 1 end puts result b # will return b to caller end def counter2 this_b = counter # capture the return value this_b.inject {|sum, element| sum+element} # total is returned to caller end end test = MyArray.new puts test.counter2 ==== Hope that helps, Eric ==== LearnRuby.com offers Rails & Ruby HANDS-ON public & ON-SITE workshops. Ruby Fundamentals Wkshp June 16-18 Ann Arbor, Mich. Ready for Rails Ruby Wkshp June 23-24 Ann Arbor, Mich. Ruby on Rails Wkshp June 25-27 Ann Arbor, Mich. Ruby Plus Rails Combo Wkshp June 23-27 Ann Arbor, Mich Please visit http://LearnRuby.com for all the details.