简体   繁体   中英

How to merge hash results from an API in Ruby?

I am retrieving subscriber information from our email provider's API. They return a hash of 25 subscribers per page. I would like to merge the results from each page into one hash (@members_subs_all). However, while my method returns the @members_subs correctly @members_subs_all does not contain any data.

Is merging the right approach? If so, what am I missing to make this work correctly? If not, what should I do differently?

def retrieve_members_info
  @members_subs_all = {}
  pages =* (0..1000)
  pages.each do |i|
    @members_subs = # API returns hash of 25 subscribers per page 
      @members_subs_all.merge(@members_subs)
      break if @members_subs["data"].empty?
  end
  puts "members_subs_all #{@members_subs_all["data"]}"
end

You want merge! rather than merge . merge returns the value of the merged hashes, but doesn't change the hash it's called on. merge! returns the value of the merged hashes and updates the hash it's called on to that value.

Compare the docs on each:

Note also that this is a pattern for naming in Ruby and Ruby libraries:

  • method returns the value of some change to the caller, but doesn't change the caller's value permanently.
  • method! returns the value of the change and updates the caller with that value.

(See also method? which are predicates that return a truthy value based on whether or not method is true of the caller.)

def merge_hashs(a,b)
  a.merge(b) {|key, a_v, b_v| merge_hashs(a_v, b_v) }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM