5

How do I replace age with 31?

[{"name"=>"Bob"}, {"age"=>"30"}]
1
  • 1
    If Bob is 30, the attributes should be in the same hash, since they represent the same person: [{"name"=>"Bob", "age"=>"30"}] Commented Feb 27, 2020 at 23:48

5 Answers 5

10

Another way, using find

1.9.3p194 :007 > array1 = [{"name"=>"Bob"}, {"age"=>"30"}]
 => [{"name"=>"Bob"}, {"age"=>"30"}] 
1.9.3p194 :008 > hash1 = array1.find { |h| h['age'] == "30" }
 => {"age"=>"30"} 
1.9.3p194 :009 > hash1['age'] = 31
 => 31 
1.9.3p194 :010 > array1
 => [{"name"=>"Bob"}, {"age"=>31}]
Sign up to request clarification or add additional context in comments.

Comments

9

using map! (will replace age value in all hashes that contain it)

a = [{"name"=>"Bob"}, {"age"=>"30"}]
a.map! do |h|
  h['age'] = 31 if h['age']
  h
end
a
=> [{"name"=>"Bob"}, {"age"=>31}]

Comments

3

Why not convert the array into something easier and more flexible to work with? Your array is crying out to be a value object:

class Person
  attr_accessor :name, :age
  def initialize arr
    arr.each { |h| h.each { |k,v| instance_variable_set("@#{k}", v) } }
  end
  def to_hash_array
    instance_variables.each_with_object([]) do |iv, arr|
      arr << {iv.to_s.sub('@','') => instance_variable_get(iv)}
    end
  end
end

def hash_array_to_person arr
  person = Person.new
  arr.each { |h| h.each { |k,v| person.send("#{k}=", v) } }
  person
end

example = [{"name"=>"Bob"}, {"age"=>"30"}]
bob = Person.new(example)

p bob
p bob.to_hash_array
bob.age = 31
p bob.to_hash_array

Output:

#<Person:0x00000000fe8418 @name="Bob", @age="30">
[{"name"=>"Bob"}, {"age"=>"30"}]
[{"name"=>"Bob"}, {"age"=>31}]

Ruby isn't C, you have so much more available to you than the basic primitive data types.

Comments

2

Since what you really have is an array of hashes, you can index the array to get the second hash and then update the value by passing "age" as the key:

1.9.3p194 :001 > h = [{"name"=>"Bob"}, {"age"=>"30"}]
 => [{"name"=>"Bob"}, {"age"=>"30"}] 
1.9.3p194 :002 > h[1]["age"] = 31
 => 31 
1.9.3p194 :003 > h
 => [{"name"=>"Bob"}, {"age"=>31}] 

Comments

1

This will do:

[{"name"=>"Bob"}, {"age"=>"30"}][1]["age"] = 31

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.