From: Eva on 23 Dec 2009 21:36 Hi, Please take a look at below: def mytest return [1..10] end x = mytest x.each do |c| puts c end this works not as I expected. I want the output of: 1 2 3 4 5 6 7 8 9 10 But if I change return [1..10] to return 1..10 it will work. So what's the difference between 1..10 and [1..10]? THanks.
From: Steve Klabnik on 23 Dec 2009 21:47 [Note: parts of this message were removed to make it a legal post.] 1..10 is a range, while [1..10] is an array with one element, a range from 1..10. You can think of 1..10 as (1..10) and [1..10] as [(1..10)] I am 95% sure that this is correct, someone please correct me if I'm wrong. irb seems to support this: > def one_to_ten > 1..10 > end => nil > one_to_ten.class => Range > [1..10].class => Array
From: Eva on 23 Dec 2009 22:29 On Thu, 2009-12-24 at 11:47 +0900, Steve Klabnik wrote: > 1..10 is a range, while [1..10] is an array with one element, a range from > 1..10. You can think of 1..10 as (1..10) and [1..10] as [(1..10)] > > I am 95% sure that this is correct, someone please correct me if I'm wrong. > irb seems to support this: > > > def one_to_ten > > 1..10 > > end > => nil > > one_to_ten.class > => Range > > [1..10].class > => Array Thanks for the reply. I'm newbie to Ruby,so have another question, I want to make a function who returns the result which can be used as: mytest do |a,b|c| do_something end How to write this mytest? Regards, Eva
From: Justin Collins on 24 Dec 2009 00:48 Eva wrote: > On Thu, 2009-12-24 at 11:47 +0900, Steve Klabnik wrote: > >> 1..10 is a range, while [1..10] is an array with one element, a range from >> 1..10. You can think of 1..10 as (1..10) and [1..10] as [(1..10)] >> >> I am 95% sure that this is correct, someone please correct me if I'm wrong. >> irb seems to support this: >> >> > def one_to_ten >> >>> 1..10 >>> end >>> >> => nil >> >>> one_to_ten.class >>> >> => Range >> >>> [1..10].class >>> >> => Array >> > > > Thanks for the reply. I'm newbie to Ruby,so have another question, I > want to make a function who returns the result which can be used as: > > mytest do |a,b|c| do_something end > > How to write this mytest? > > Regards, > Eva > > The do...end is actually creating a block, which is passed into your method. There are two ways of having functions accept blocks: #Explicitly def mytest &block block.call 1, 2, 3 end #Implicitly def mytest yield 1, 2, 3 end Either way can be called like mytest do |a,b,c| do_something_with a, b, c end You will probably want to read up on methods and blocks and how the two can be used together. -Justin
From: Eva on 24 Dec 2009 00:54 Thanks all! Merry Christmas Ruby world. -- Kind Regards, Eva.
|
Next
|
Last
Pages: 1 2 Prev: log4r unpack problems Next: bluecloth 2.0.5 installation error on Windows |