I am trying to call the method details
for object Person
that is storred in array resut
but keep getting this error undefined method 'details' for [#<Person:0x000001e277d58aa8 @name="Winston", @age=3>, #<Person:0x000001e277d58940 @name="Rob", @age=1>, #<Person:0x000001e277d58788 @name="Sam", @age=5>]:Array (NoMethodError)
This is the code that is throwing the error result.each { |p| p.details}
. It is the last line of code. I am not sure why this is throwing an error and am even more confused becuase I made similar method calls earlier and they are not throwing errors.
class Person
def initialize(name, age)
@name = name
@age = age
end
def details
puts "Name: #{@name}\nAge: #{@age}"
end
def get_age
return @age
end
end
def generate_data(names)
sample_pool = []
names.each { |n| sample_pool << Person.new(n, rand(100)) }
return sample_pool
end
def extract(sample_pool, criteria)
result = []
result << sample_pool.select { |n| n.get_age <= criteria}
return result
end
names = ["Doug", "Matt", "Fred", "Fransisco", "Pete", "Rick", "Rob", "Tanner", "Greg", "Sherri", "Winston", "Sam", "Brett", "Georgia", "Alison", "Grant", "Brick", "Slick", "Van", "Fawn", "Sloan", "Harry", "Ron", "Jerry", "Jasmine", "Dawn", "Misty"].shuffle!
puts "Enter an age that you would like to search up too."
criteria = gets.chomp.to_i
sample_pool = generate_data(names)
result = extract(sample_pool, criteria)
result.each { |p| p.details}
CodePudding user response:
select
returns an array, and <<
pushes the return value of select
into result
.
This means that result
is a nested array. It looks like this:
[[Person<name: rob>, Person<name: Sam>, Person<name: Winston>]]
You want to create a flat array, so you could change extract
to be something like this:
def extract(sample_pool, criteria)
sample_pool.select { |n| n.get_age <= criteria}
end
CodePudding user response:
TonyArra answered your original question by modifying your extract
method, but you mentioned in your comment, your generate_data
method.
The use of the each method in generate_data
adds a single Person
for each name in your names
Array, so you get what you expect, however a better way to implement that is to use map
to "map" the String
Array
names
into a Person
Array
def generate_data(names)
names.map {|n| Person.new(n, rand(100))}
end