Prateek Agarwal wrote:
> I am getting the follower
> `+': Range can't be coerced into Fixnum (TypeError)
> 
> How to get rid of this?

You need to take a methodical approach to debugging. Fortunately, your 
code is small and complete so I can run it here to get the backtrace.

$ ruby Question5.rb
Question5.rb:19:in `+': Range can't be coerced into Fixnum (TypeError)
  from Question5.rb:19
  from Question5.rb:16:in `each'
  from Question5.rb:16
  from Question5.rb:14:in `loop'
  from Question5.rb:14

So what's line 19?
  flag=flag+check

Clearly, one of these values is bad. So now insert a statement before 
this line to show you the values just before the error occurs, like 
this:

  STDERR.puts "flag=#{flag.inspect}, check=#{check.inspect}"
  flag=flag+check

$ ruby Question5.rb
flag=0, check=1
flag=0, check=1..2
Question5.rb:20:in `+': Range can't be coerced into Fixnum (TypeError)
  from Question5.rb:20
  from Question5.rb:16:in `each'
  from Question5.rb:16
  from Question5.rb:14:in `loop'
  from Question5.rb:14

There's your problem. The second time round the loop, check is the range 
1..2 and you are trying to calculate 0 + (1..2) which doesn't make 
sense.

So now you ask, why does check have this value? That's easy, it's 
assigned in the line before, and it's the return value from 
checkforcube(remainder). So this function is returning a range, which 
you weren't expecting.

Now you just have to remember that the return value of a method is the 
value of the last expression evaluated; and the value of a 'for' loop is 
the object being iterated over.

>> def foo; (1..3).each { puts "hi" }; end
=> nil
>> foo
hi
hi
hi
=> 1..3
   ^^^^

>> def foo; (1..3).each { puts "hi" }; return 0; end
=> nil
>> foo
hi
hi
hi
=> 0
   ^

You can probably do this sort of debugging with -rdebug or an IDE or 
some other breakpoint facility, but I just use puts. There's less 
learning, and it works in just about every environment.

HTH,

Brian.
-- 
Posted via http://www.ruby-forum.com/.