How do I iterate over an array of hashes and return the values in a single string?

前端 未结 2 1026
一个人的身影
一个人的身影 2020-12-28 22:18

Sorry if this obvious, I\'m just not getting it. If I have an array of hashes like:

people = [{:name => \"Bob\", :occupation=> \"Builder\"}, {:name =&         


        
2条回答
  •  暖寄归人
    2020-12-28 23:01

    Here you go:

    puts people.collect { |p| "#{p[:name]}: #{p[:occupation]}" }
    

    Or:

    people.each do |person|
      puts "#{person[:name]}: #{person[:occupation]}"
    end
    

    In answer to the more general query about accessing the values in elements within the array, you need to know that people is an array of hashes. Hashes have a keys method and values method which return the keys and values respectively. With this in mind, a more general solution might look something like:

    people.each do |person|
      puts person.values.join(': ')
    end
    

提交回复
热议问题