简体   繁体   中英

Can't loop through values in a hash

I am pretty new to Ruby. I am cobbling together something like this:

in_msg.updateComments.map{|c| c.each} do |comment|

in_msg.updateComments is a hash.

but I get the error:

SyntaxError: /Users/alexgenadinik/projects/cmply/cmply-app/app/models/linked_in_update.rb:65: syntax error, unexpected kDO, expecting kEND
      in_msg.updateComments.map{|c| c.each} do |comment|

Any idea how to do this correctly?

The data comes in like this:

 "updateComments"=>{"values"=>[{"comment"=>"Sweet", "person"=>{"siteStandardProfileRequest"=>{"url"=>"http://www.linkedin.com/profile?viewProfile=&key=23676551&authToken=FHXz&authType=name&trk=api*a140290*s148640*"},

First of all. Here is the link to Hash object . We don not need map method to iterate through hash. Iterations through Hash are done using each , each_pair , each_key , each_value methods. See the previously provided link for usages and syntax.

in_msg.updateComments.each do |key, value|
  p key #prints "values" string on first loop
  value.each do |k, v|
    p k #prints "comment", "person"
    p v #prints "Sweet", "{"siteStandardProfileRequest"=>{"url"=>"http://www.linkedin.com/profile?viewProfile=&key=23676551&authToken=FHXz&authType=name&trk=api*a140290*s148640*"}"
  end
end

Looks like you're confused about how to use blocks.

in_msg.updateComments.each do |key, value|
   # code here...
end

OR

in_msg.updateComments.each {|key, value| code_here }

Update : now that you posted your data... looks like you have several nested hashes and arrays. I'd recommend finding a good tutorial on both ruby arrays and ruby hashes.

I believe the syntax you're looking for is this:

in_msg.updateComments.map { |c| 
  c.each  do |comment| 
     # do stuff for each comment
  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