0

I have an array of hashes as below

status_arr = [{id: 5, status: false}, 
              {id: 7, status: false}, 
              {id: 3, status: false},
              {id: 9, status: false} ]

I would like to update the hash with status: true if it has ids 5, 7

update_ids = [5, 9]

I am trying the following and has no idea to proceed

status_arr.select{ |arr| update_ids.include?(arr[:id]) arr[:status] = true}

Expected output:

status_arr = [{id: 5, status: true}, 
              {id: 7, status: false}, 
              {id: 3, status: false},
              {id: 9, status: true} ]
3
  • 1
    You are actually very close you could just change this status_arr.select{ |arr| update_ids.include?(arr[:id]) arr[:status] = true} to status_arr.select{ |arr| update_ids.include?(arr[:id])}.each{|arr| arr[:status] = true} or status_arr.each{ |arr| arr[:status] = update_ids.include?(arr[:id]) } Commented Sep 6, 2018 at 13:27
  • You can do this. status_arr.select{ |arr| arr[:status] = true if update_ids.include?(arr[:id])} Commented Sep 6, 2018 at 13:32
  • 1
    status_arr.map { |h| h.merge(status: [5,9].include?(h[:id])) } Commented Sep 6, 2018 at 13:44

1 Answer 1

1
require 'set'
update_ids = Set.new([5,3])
status_arr.map{ |s| s[:status] = update_ids.include?(s[:id]); s }
#=> [{:id=>5, :status=>true}, {:id=>7, :status=>false}, {:id=>3, :status=>true}, {:id=>9, :status=>false}]

instead of Set you can use just a Hash

update_ids = {5 => true, 3=> true}
status_arr.map{ |s| s[:status] = update_ids.include?(s[:id]); s }
#=> [{:id=>5, :status=>true}, {:id=>7, :status=>false}, {:id=>3, :status=>true}, {:id=>9, :status=>false}]

Or an array, but it will have some performance issues for big arrays

update_ids = [5,3]
status_arr.map{ |s| s[:status] = update_ids.include?(s[:id]); s }
#=> [{:id=>5, :status=>true}, {:id=>7, :status=>false}, {:id=>3, :status=>true}, {:id=>9, :status=>false}]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.