Archive for the ‘ruby’ Category

Ruby callbacks (hooks)

Wednesday, March 31st, 2010

Hooks are a fascinating bit of Ruby magic. They are methods you can define with actions to run when something happens. You can put triggers in your code.

This blog post explains them very well; and for more information, get “Metaprogramming Ruby”, which is a great book – not only about the callbacks, but about a host of information.

New gem: ListBrowser

Friday, January 15th, 2010

~~~~ ListBrowser README ~~~~

I was working on a parser for a very specific tree structure, and was frustrated that there wasn’t a simple way to parse it in irb. “What??”, I thought. “I have to use my brain?! God forbid!”. So I set to using my brain a little more to create this tool. It’s not much, but maybe it’ll make someone’s life a little easier.

Install: (set up gemcutter)
gem install ListBrowser

It can be used in irb, and really should be used there – when you call it on a tree structure, you’ll get a menu with a list of choices on how you want to go through whatever structure you gave it.

In my particular, special case, I would do something like this:

require ‘sgf_parser’ # For my tree structure require ‘list_browser’ # For this.

tree = SgfParser::Tree.new :filename => “kogo.sgf”

ListBrowser.new tree.root, ‘parent’, ‘children’, ‘properties’

# And follow the menu!

In my particular case, I would not need to enter those strings, as they
just happen to be the names I chose for my tree structure, but they should
serve as a good enough example!

Ruby SgfParser now really working!

Thursday, December 31st, 2009

Thanks @alfmikula, it saves properly and has even been gemified. I will soon push it to gemcutter and maybe put a homesite on Rubyforge, not sure.
It can be found at http://github.com/Trevoke/SGFParser for now, get the code while it’s hot! :-)

Random constrained permutations in Ruby

Thursday, December 17th, 2009

Look, Ma, these are my baby steps in algorithms!

# list is the elements to be permuted
# y is the number of results desired
# z is the number of elements per result
# equalizer keeps track of who got used how many times
def constrained_permutations list, y, z
  list.uniq! # Never trust the user. We want no repetitions.
  equalizer = {}
  list.each { |element| equalizer[element] = 0 }

  results = []
  # Do this until we get as many results as desired
  while results.size < y
    pool = []
    puts pool
    least_used = equalizer.each_value.min
    # Find how used the least used element was
    while pool.size < z
      # Do this until we have enough elements in this resultset
      element = nil
      while element.nil?
        # If we run out of "least used elements", then we need to increment
        # our definition of "least used" by 1 and keep going.
        element = list.shuffle.find do |x|
          !pool.include?(x) && equalizer[x] == least_used
        end
        least_used += 1 if element.nil?
      end
      equalizer[element] += 1
      # This element has now been used one more time.
      pool << element
    end
    results << pool
  end
  return results
end

constrained_permutations [0,1,2,3,4,5,6], 6, 2
=> [[4, 0], [1, 3], [2, 5], [6, 0], [2, 5], [3, 6]]
constrained_permutations [0,1,2,3,4,5,6], 6, 2
=> [[4, 5], [6, 3], [0, 2], [1, 6], [5, 4], [3, 0]]

Inter-array permutations in Ruby

Thursday, December 17th, 2009

I don’t really have a better name for this. It’s also not completely clean, but it works. I had, almost a year ago (362 days ago), written a blog post about lexicographic permutations. That was about permutations of elements within one array.
Someone on ruby-forum asked about permutations between multiple arrays. I found something in C#, which I was happy to transcribe to Ruby and tweak a little.

def array_permutations array, index=0
  # index is 0 by default : start at the beginning, more elegant.
  return array[-1] if index == array.size - 1 # Return last element if at end.
  result = []
  array[index].each do |element| # For each array
    array_permutations(array, index + 1).each do |x| # Permute permute permute
      result << "#{element}, #{x}"
    end
  end
  return result
end

So, we get this:

first = ['one', 'two']
second = ['three', 'four']
third = 'five', 'six']
result = array_permutations [first, second, third]
=> ["one, three, five", "one, three, six", "one, four, five", "one, four, six", "two, three, five", "two, thre
e, six", "two, four, five", "two, four, six"]

Magic!

——
Edit – of course, my solution is hackish, and someone came up with a quicker and more elegant solution:

def fancy_array_permutation array
  return array[0] if array.size == 1
  first = array.shift
  return first.product( fancy_array_permutation(array) ).map {|x| x.flatten.join(" ")}
end

This gives the same result as above.

Open source is wide open: Calling RAKE tasks

Tuesday, December 15th, 2009

Open source is wide open: Calling RAKE tasks.

Good to know.

On re-reading old code

Wednesday, December 9th, 2009

I came across this beauty:

def same_modality? list
  check = list[0][0]
  list.each do |i|
    return false if check != i[0]
  end
  return true
end

This was “necessary” because I got an array of one-element arrays back, and I wanted to check whether or not that one element was the same across the array.

Three seconds of thinking made me realize that just maybe, I could do this:

list.uniq.size == 1

I -like- Ruby.

Auto-vivifying hashes in Ruby

Friday, November 6th, 2009

An auto-vivifying hash is a hash that lets you create sub-hashes automatically. This means that the following code becomes possible:

def cnh # silly name "create nested hash"
  Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
end
my_hash = cnh
my_hash[1][2][3] = 4
my_hash # => { 1 => { 2 => { 3 =>4 } } }

This is useful because it reduces the amount of logic in the code. No more “If sub-hash doesn’t exist, create it!”

Courtesy of Robert Klemme on www.ruby-forum.com

_____

Update:

Facets has a way of doing an auto-vivifying hash, too! Thanks to Stackoverflow.

# Monkey patching Hash class:
# File lib/core/facets/hash/autonew.rb, line 19
  def self.autonew(*args)
    leet = lambda { |hsh, key| hsh[key] = new( &leet ) }
    new(*args,&leet)
  end

The standard new method for Hash accepts a block. This block is called in the event of trying to access a key in the Hash which does not exist. The block is passed the Hash itself and the key that was requested (the two parameters) and should return the value that should be returned for the requested key.

You will notice that the leet lambda does 2 things. It returns a new Hash with leet itself as the block for handling defaults. This is the behaviour which allows autonew to work for Hashes of arbitrary depth. It also assigns this new Hash to hsh[key] so that next time you request the same key you will get the existing Hash rather than a new one being created.

Sweet deal!

Closures in Ruby

Wednesday, October 28th, 2009

I found a script that explains everything really well.
Credit goes to:
# CLOSURES IN RUBY Paul Cantrell http://innig.net
# Email: username “cantrell”, domain name “pobox.com”
Along with this blog entry, it’s made the whole deal much easier to figure out.

Now.. Why didn’t I get that when I was looking at LISP?

Extending Ruby for Fun and Profit

Tuesday, October 27th, 2009

Wow. I just watched Dave Thomas’ talk Ruby Metaprogramming: Extending Ruby for Fun and Profit and it explained so many things.

It’s quite worth watching if you like Ruby and don’t know about metaprogramming and Ruby hooks and what ‘self’ means, fully.