r00k
(Ben Orenstein)
April 8, 2015, 5:34pm
1
Continuing the discussion from New trail: Ruby Challenges :
I started this ruby challenge but I feel like I went about the wrong way to approach this. This is the first exercise to analyze Macbeth. So I used nokogiri gem to parse the xml.
@doc = Nokogiri::HTML(open("http://www.ibiblio.org/xml/examples/shakespeare/macbeth.xml"))
Then I took out all the speech and return them as array.
all_speeches = @doc.xpath("//speech").remove.to_a
From the array of arrays, I made an array of hashes for each speaker and their lines.count:
a = all_speeches.map{ |s| { s.css("speaker/text()").to_s => s.css("line").count } }
This is where I went to stackoverflow for help. I want to combine values of hashes with the same key.
Stackoverflow suggested:
cache = Hash.new { |h, k| h[k] = { k => 0 } }
puts a.flat_map(&:to_a).each_with_object(cache) { |(k,v),h| h[k][k] += v }.values
Those two lines did the trick, but I am having a hard time understanding what is going on. especially h[k][k]
in the block. I know a new hash was created called cache, and it is passed into each_with_object(). I don’t know if this is the best way to go about solving this exercise. For me this is crazy ruby, haha. Any pointers will help. Thanks in advance!
I think the root issue is that you’re not sure how each_with_object
works. That’s okay, by the way .
Let’s simplify the example a little bit. I’m going to give you a simpler challenge that I think will help you understand things.
Write a method that takes an array of strings and returns a hash where the keys are the strings, and the values are their lengths.
Example:
def strings_to_lengths(strings)
# You write this part. Use each_with_object.
end
# Expected results:
strings = ["ben", "eric", "nathan"]
strings_to_lengths(strings) # Returns: { "ben" => 3, "eric" => 4, "nathan" => 6 }
I think when you solve this, you’ll be well on your way to understanding how your more-complicated example works.
1 Like
christoomey
(Chris Toomey)
Split this topic
May 4, 2015, 8:37pm
2
This topic is now unlisted. It will no longer be displayed in any topic lists. The only way to access this topic is via direct link.
Hi, this is my first attempt at Upcase and I’m struggling to push the repo. I am doing…
git push origin master
However I am getting the following error:
remote: error: insufficient permission for adding an object to repository database objects
remote: fatal: failed to write object
error: unpack failed: unpack-objects abnormal exit
To git@git.upcase.com :tommotaylor/analyzing-shakespeare.git
! [remote rejected] master → master (unpacker error)
error: failed to push some refs to ‘git@git.upcase.com:tommotaylor/analyzing-shakespeare.git’
Any help would be great