I am looking to set up a hash with an array as the value i.e.,
customers = {first: [name, age, height, etc], second: [name, age, height, etc], ...}
How can I access and edit the customers specific attributes such as customers[first[age]]?
If your individual customers data is an Array like you showed then you need it to have fixed indexes for those attributes, like name always at index 0, age at index 1 and you can access the data by doing
customers[:first][0] # name
customers[:first][1] # age
customers[:first][2] # height
but if you control how the data is being generated then you should use Ruby Hash for this purpose so the generated data should be in this format, an array of hashes
customers = [{ name: 'John Doe', age: 30, height: 175 }, { name: 'John Doe', age: 30, height: 175 }]
and you can now do
customers.first[:name] # for first customer
customers[0][:age] # for first customer
customers[1][:name] # for second customer
customers = {first: [name, age, height, etc]} or customers = [{ name: 'John Doe', age: 30, height: 175 }] ?Since you asked for a different way to set up this data structure, here's another option:
Set up a class Customer
class Customer
attr_accessor :name, :age, :height
def initialize(name:, age:, height:)
@name = name
@age = age
@height = height
end
end
Then however you set up your collection, either an array or a hash, you can access the elements attributes by calling a method on the object.
Here's an array example:
customers = [
Customer.new(name: "John", age: 30, height: 175),
Customer.new(name: "Sam", age: 25, height: 160)
]
Then you could access the elements as
customer[0].name
# => "John"
customer[0].name = "Tom"
# => "Tom"
customer[1].age
# => 25
# etc...
customers[:first][1]a try (assumes age is always the second element).name,age, etc.) intended to be variables or methods? If they are meant to be literals you need to make them strings ("name") or symbols (:name).