Rainy days and Java always get me down


I've Moved My Blog

It's currently located at http://www.urlinone.com/blog

I should say "I'm moving my blog." It's a pretty painful process.

Pebble has blown up on me, and it's been many months since I've been able to blog reliably. I've lost posts. And now I've got to figure out how to migrate my past blog posts from Pebble to my new destination without all the URLs changing, lest external links become 404 Not Founds.

Why does everything in the 21st century have to be a three-day project???

Let's say you define a simple Hash.

irb(main):001:0> h1 = {"a"=>1,"b"=>2,"c"=>3}
=> {"a"=>1, "b"=>2, "c"=>3}

What do you think you'll get when you send an each message to it? I figured either a, b, c or 1, 2, 3. Surprise:

irb(main):003:0> h1.each{|a| puts a}
a
1
b
2
c
3
=> {"a"=>1, "b"=>2, "c"=>3}

It all comes out, keys and values interleaved.

Now, the trick becomes figuring out what to Google for to learn the syntax that gets you just the part of the hash you're after. Let me save you a little time. What you're after is each_value.

irb(main):008:0> h1.each_value {|a| puts a}
1
2
3
=> {"a"=>1, "b"=>2, "c"=>3}

You can also use each_key. Fairly intuitive, once you know it. Ah, there's the rub. :-)

irb(main):009:0> h1.each_key {|a| puts a}
a
b
c
=> {"a"=>1, "b"=>2, "c"=>3}

Your problem was that the block Hash#each takes is really looking for a |key, value| . Your code should read: h1.each { |key, val| ... } http://ruby-doc.org/core/classes/Hash.html#M000635
Yep, cool. Thanks, Tony!
irb(main):043:0> h1.each{|k,v| puts "#{k} ---> #{v}"}
a ---> 1
b ---> 2
c ---> 3
=> {"a"=>1, "b"=>2, "c"=>3}

This reminds me of something else that has been bugging me since I saw it. What does this syntax mean?

def list
  @category_pages, @categories = paginate :category, :per_page => 10, :order_by => 'category'
end
How can Ruby return two values from the paginate method?!



Add a comment

Title
Body
HTML : b, i, blockquote, br, p, pre, a href="", ul, ol, li
Name
E-mail address
Website
Remember me Yes  No 

E-mail addresses are not publicly displayed, so please only leave your e-mail address if you would like to be notified when new comments are added to this blog entry (you can opt-out later).

TrackBack to http://www.leegrey.com/hmm/addTrackBack.action?entry=1124303193372