I have an array of objects with one instance variable:
oranges_array =
[#<Orange:0x007faade859ea0 @diameter=2.7>,
#<Orange:0x007faade859ef0 @diameter=2.8>,
#<Orange:0x007faade859f40 @diameter=2.6>]
For example, how would I access the diameter instance variables? I want to eventually get their average. Do I need to or am I on the right track in thinking I maybe use an each loop to shovel each diameter into its own array then use inject
? Or is there a simpler way to access the diameter variables? Thanks!
One option is to add attr_reader
to Orange
class:
class Orange
attr_reader :diameter
end
Now you can get the avarage:
avg = oranges_array.map(&:diameter).inject(:+) / oranges_array.size.to_f
# with Ruby 2.4+ you can do the following:
# avg = oranges_array.sum(&:diameter) / oranges_array.size.to_f
Another option is to use Object#instance_variable_get
(without having to add the attr_reader
to the class:
avg = oranges_array.map { |orange| orange.instance_variable_get(:@diameter) }.inject(:+) / oranges_array.size.to_f
Using instance_variable_get
for this task is the last resort option and I added it almost exclusively to show there's a way to get instance variables of objects in case there is, for example, no way to define attribute readers in the class.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments