From: Brian Candler Date: 2008-12-01T23:46:11+09:00 Subject: Re: Control Structures Like many languages, there are lots of ways to do things. Using a block with Array.new lets you initialise an Array with n elements in one go, where the block is invoked n times to create each element. I think that comparing monkey == monkey.sort is the easiest way to check for values in sequence, but a more esoteric way is using Enumerable#each_cons to check each pair in turn. So this gives the following solution: require 'enumerator' puts "How many elements?" a = Integer(gets) loop do monkey = Array.new(a) { rand(a) } out_of_order = false monkey.each_cons(2) { |x,y| if x > y out_of_order = true break end } puts "#{monkey.inspect}, out_of_order=#{out_of_order}" end Now, you can squeeze this a bit more, because each_cons normally returns nil, but break can pass a different return value. This gives: loop do monkey = Array.new(a) { rand(a) } out_of_order = monkey.each_cons(2) { |x,y| break true if x > y } puts "#{monkey.inspect}, out_of_order=#{out_of_order ? "yes" : "no"}" end Now, to get really funky. The Enumerable module has a bunch of methods for operating on sequences of objects which are yielded by the 'each' method. Using to_enum you can insert a proxy object which maps the call to #each to a call to another method - such as #each_cons. So then you get: loop do monkey = Array.new(a) { rand(a) } out_of_order = monkey.to_enum(:each_cons,2).find { |x,y| x > y } puts "#{monkey.inspect} #{out_of_order && "bad monkey!"}" end I certainly wouldn't have written that as a newcomer to Ruby :-) But it's nice to know that, when you have mastered the basics, there's lots more to chew on. Regards, Brian. P.S. Try all this stuff in irb. For example, to try out each_cons: irb(main):001:0> require 'enumerator' => true irb(main):002:0> [1,2,3,4,5].each_cons(2) { |x| p x } [1, 2] [2, 3] [3, 4] [4, 5] => nil -- Posted via http://www.ruby-forum.com/.