2

In the following how should I call this method properly?

Here's the exmaple where I try to call randomMethod() and an error throws saying it is undefined.

def randomMethod()

  rand1 = rand(2)
  if rand1 == 1

    rand2 = rand(1..25)
    puts rand2
    puts ""

  else
    rand2 = 0
    puts rand2
    puts ""
  end
end

x = 99
while x > 0
  randomMethod()
  x - rand2 
end
gingervitiis
  • 105
  • 5

3 Answers3

8
#use this kind of convention about name of function
def random_method()
    #always initialize your varialble first before implement to avoid errors
    rand1 = rand(2)
    rand2 = 0

    if rand1 == 1
      rand2 = rand(1..25)
    end

    #don't repeat yourself
    puts rand2
    puts ""

    #pick a return just to make sure you do not mistaken
    return rand2
end


x = 99
while x > 0
    rand2=random_method()
    x - rand2
    x = x - 1
end
Tau-fan Ar-if
  • 380
  • 3
  • 8
3

You haven't return the rand2 value from the randomMethod method and also you haven't received as well. I modified your program, check it now.

def randomMethod()

  rand1 = rand(2)
  if rand1 == 1

    rand2 = rand(1..25)
    puts rand2
    puts ""

  else
    rand2 = 0
    puts rand2
    puts ""
  end
  rand2
end

x = 99
while x > 0
  rand2=randomMethod()
  x - rand2
  x-=1
end
Rajagopalan
  • 4,496
  • 2
  • 7
  • 25
  • That fixed the error i was getting. Now what im trying to solve is the infinite loop if anyone has a suggestion. – gingervitiis Aug 08 '19 at 03:31
  • @Amadan Actually I took his program and modified the problematic area. Now I have updated. – Rajagopalan Aug 08 '19 at 03:36
  • @gingervitiis Updated with `x-=1`. you can check now. – Rajagopalan Aug 08 '19 at 03:36
  • Im glad its functional now. However the goal of this program is to subtract the number generated in line 6 and subtract it from x. So when x hits 0 thats when the random numbers are shown in the console. For example generating a 25 4 times would end the program because 100 > 99 – gingervitiis Aug 08 '19 at 03:49
3

You cannot access local method variables from outside the method itself:

def my_method
  @val1 = 1
  val2 = 2
end

my_method #=> 2 returns the value of the last line of the method
@val1 #=> 1 (or you get nil unless you call my_method before)
val2 #=> undefined local variable or method `val2`

Check this post Difference between various variables scopes in ruby


You could rewrite your method like this:
def random_method
  return rand(1..25) if rand(2) == 1
  0 # return value unless the condition above
end

Note that it doesn't assure that 50% of the times returns a number between 1 and 25, but the probability is 50%.

Then use Kernel#loop for the iteration, you need to decrement x:

x = 99
loop do
  puts "x = #{x}"
  x -= random_method # decrement x by the value returned by random_method
  break if x <= 0
end
iGian
  • 10,602
  • 3
  • 18
  • 34