Posts Tagged ‘ruby’

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.

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!

SGF Parser updated

Monday, October 12th, 2009

Someday I’ll come out with a proper revision numbering scheme for it.
I’ve implemented some Cucumber testing, the code now actually parses SGF files properly, including the KGS ones, it’ll work on Ruby 1.8.6, 1.8.7, 1.9.1, so .. It’s all good on that front.

The code’s not as clean as I’d like it to be, and probably not as commented, either.

http://github.com/Trevoke/SGFParser

I am not -saving- SGF files with it yet, but heck if I’m not parsing them. And now YOU can, too !

Ruby SGF Parser

Tuesday, September 15th, 2009

So, I play weiqi (known as the game of go, but I prefer using the chinese name).
There are some SGF parsers out there for Ruby, but I wanted to write my own – the other ones didn’t seem comprehensive enough, didn’t seem Ruby-like enough in their objectifiying the women data.
My original goal was twofold: write a script to rename all the SGF files in my collection so they can be easily parsed later, and … Learn more Ruby!
Here is the github link: http://github.com/Trevoke/SGFParser
It’s a work in progress. Right now it parses the SGF file properly, but the user has a fair amount of work to do to use the data.. Which, maybe, is the way it needs to be. But I’m gonna try to follow the principle of least surprise to the bitter end! :)

Ruby on Rails + Sybase

Friday, July 31st, 2009

Caveat: This adapter may only work with the enterprise edition of Sybase (i.e. Sybase ASE) not with SQLAnywhere (Sybase ASA)

gem install activerecord-sybase-adapter -s http://gems.rubyonrails.org

ActiveRecord::Base.establish_connection(
:adapter => “sybase”,
:database => “test”,
:host => “www.yourdbserver.com”,
:username => “kevin”,
:password => “test”)

Play!

Redcar 0.1 on Ubuntu with Ruby 1.8 – success

Wednesday, April 22nd, 2009

And all I did was follow the instructions in the readme.. Now to play with the software!
www.redcareditor.com