-1

Simple problem in looping and dynamic assignment, need suggestion.

Problem:

@var = 1

def meth
 @values = (#here a query uses @var value to calculate and returns some values)
end

meth #calling meth function

# value of @value increaser when i increase @var
# i need to increment @var by 10 each time and have to call meth for @values=10

if @values.lenght < 10
 # Here how can i iterate 
  10.times do |x|
  @var += 10
  meth 
 end
 # calling meth with incremented value @var
end

I am not getting how to iterate the the method.

Aparichith
  • 1,452
  • 4
  • 20
  • 40
  • what is your expected output? and what do you get instead? – 23tux Jul 02 '14 at 12:22
  • i supposed to get 10 '@values'. Mean for '@var = 1' ,i run 'meth' function ,if i dint get 10 '@values' i need to increment '@var' value and again run the 'meth' function. – Aparichith Jul 02 '14 at 12:30

1 Answers1

1

You have to initialize @values before using it, otherwise it seems to work:

@var = 1
@values = []

def meth
  @values << @var
end

meth

10.times do
  @var += 10
  meth
end

p @values #=> [1, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101, 101]
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • yeah i declared that array . BUt missed iterating in loop – Aparichith Jul 02 '14 at 13:17
  • and you have to use `@values <<` instead of `@values =` in order to *add* objects to the array (`=` would replace the entire array, which is certainly not what you want) – Stefan Jul 02 '14 at 13:19