Richard Osborne
Richard Osborne

Reputation: 33

Why is this code from Ruby book not working?

I copied this out of a book. "The Ultimate Guide to Ruby Programming" Copyright (c) 2006-2016 Satish Talim http://satishtalim.com/

Please see the code and error message. Why am I getting this error?

I have checked my typing, re-entered the code, exited irb re-entered irb, re-entered the code, same result. What is my error?

irb(main):001:0> 10.times do |num|
irb(main):002:1*   square = num * num
irb(main):003:1>   return num, square
irb(main):004:1> end
Traceback (most recent call last):
        4: from C:/Ruby25-x64/bin/irb.cmd:19:in `<main>'
        3: from (irb):1
        2: from (irb):1:in `times'
        1: from (irb):3:in `block in irb_binding'
LocalJumpError (unexpected return)
irb(main):005:0>

Upvotes: 0

Views: 187

Answers (2)

TamerB
TamerB

Reputation: 1441

return is used inside methods. You are using it without one.

Try the following:

def get_my_result
    10.times do |num|
        square=num*num
        return num,square
    end
end

get_my_result()

Note: With this code, the loop will execute only once and return the value [0, 0]

Upvotes: -2

tadman
tadman

Reputation: 211540

It's not clear where this is intended to be used, but you can't return like that inside a loop.

The code is probably:

def squared
  10.times do |num|
    square = num * num

    yield num, square
  end
end

Where you'd call that somehow externally:

squared do |num, square|
  puts "The square of #{num} is #{square}"
end

A simplified version of this code is:

def square(num)
  return num * num
end

Where here return is in a valid context. Ruby tends to avoid explicit return statements unless it's intentional to avoid running the remainder of the method, as in:

 def square(num)
   if (num > 1000)
     return "That number is way too big!"
   end

   num * num
 end

Here the last statement to run (num * num) is the implicit return value of the method. Many blocks work this way, even if, where in Ruby if statements return values:

choice = if (num > 10)
  "big"
else
  "small"
end

Where choice ends up being either of those two strings depending on conditions.

Upvotes: 3

Related Questions