Unexpected 'nil' on Enumerating Over Ruby Core Array with Custom Object - Version 3.1.0
After trying multiple solutions online, I still can't figure this out. I'm learning this framework and I'm prototyping a solution and Quick question that's been bugging me - I'm testing a new approach and I'm currently working with Ruby 3.1.0 and I've run into an scenario while trying to iterate over an array that contains custom objects. The question arises when I try to access an attribute of one of the objects within the block, and I end up getting a 'nil' behavior. Here’s a simplified version of my code: ```ruby class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end people = [Person.new('Alice', 30), Person.new('Bob', 25), nil, Person.new('Charlie', 35)] people.each do |person| puts person.name # This line throws an behavior for the nil object end ``` I expected to see the names of all the persons printed out, but instead, I get the following behavior: ``` NoMethodError: undefined method `name' for nil:NilClass ``` I understand that this behavior is occurring because there’s a `nil` entry in my array. I tried to add a check to see if `person` is not `nil` before accessing the `name`, but the way I structured it didn’t work as intended: ```ruby people.each do |person| if person puts person.name end end ``` While this avoids the behavior, it still feels a bit off since I want to keep my code clean and concise. I’m also worried about performance if I have a large dataset. Is there a better way to handle this situation, perhaps using `compact` or `map`? Any advice on best practices when dealing with nil values in such enumerations would be greatly appreciated! This is part of a larger web app I'm building. What would be the recommended way to handle this? This is for a REST API running on Ubuntu 20.04. I'd really appreciate any guidance on this. Any help would be greatly appreciated!