Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a class object inside a loop

I think my question is pretty simple but I'm not flash on the fundamentals.

I have a class and I want to store data in it from a loop and access those class objects outside of the loop. For example, I want code like below

class Numbers
  attr_accessor :value

end

n = 1

while n < 10
  p = Numbers.new
  p.value = n
  n += 1
  puts p.value
end

but instead of iterating over each Number made inside of the loop, I want to store each class object and iterate over the collection outside of the initial loop. In my mind the code looks like this, but it's clearly not the right way to go about it.

class Numbers
  attr_accessor :value
end

n = 1

while n < 10
  Numbers.new
  Numbers.value = n
  n += 1
end

Numbers.each do |f|
  puts f.value
end

I ask because I want to apply this technique to a more complex problem, thank you in advance for any help you can give.

like image 890
Joel Davison Avatar asked Sep 01 '25 06:09

Joel Davison


1 Answers

Try this

class Number
  attr_accessor :value
end

numbers = (1..9).map do |n| 
  number = Number.new
  number.value = n
  number
end

How does this work?

  • map is a loop that creates an array with the result from each iteration
  • (1..9).map { |n| ... } hence creates an array of 9 number objects

I guess you are new to Ruby so here is some help with classes and objects

  • Number is a class
  • number is an object
  • Number.new creates an object that is an instance of class Number
  • value is defined by Number class and thus available on instances of that class
  • number.value is thus valid
  • Number.value is thus invalid and does not make sense
  • Use an array to store many objects

So your text should thus say

"I have a class and I want to create instances of it from a loop and access these instances outside of the loop. [...] But instead of iterating over each object made inside of the loop, I want to store each instance in an array and iterate over the array outside of the initial loop."

like image 108
akuhn Avatar answered Sep 02 '25 20:09

akuhn