Main Content

Sorta sorting a hash, and what if an exception is NOT thrown - Ruby

Archive - Originally posted on "The Horse's Mouth" - 2011-09-12 07:29:56 - Graham Ellis

Some gems from last week ...

1. Ruby's begin and rescue clauses allow you to catch anything exceptional that could derail your program. But did you know that you can also add an else clause to be run only in the event of there being no exception? There's an example from last week's Ruby course which may be found [here].

2. Many languages allow you to provide a callback (see "What is a callback?") to sort in your own way, but if you're effectively sorting a hash based on the values it contains, you've usually got to declare or have the hash global in some way. In Ruby, you can pass in a reference to the hash as part of the callback call. P.S. You CANNOT sort a hash. You're really sorting an array of the keys, and then cherry picking the members in the resultant order

Passing in:
  for ipv in counter.keys.sort { |a,b| byvalue a,b,counter }

To the function that compares:
  def byvalue (a,b,datasource)
    return datasource[b] - datasource[a]
  end


This is from the same example as the one above ...

3. Yes - I know that the word "gems" in Ruby has been used to refer to libraries and modules which you can download and install on top of / within your Ruby. I used the watir-webdriver gem for web site testing last week - see [here] - and there are many more.