Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Monday, August 31, 2009

Ruby Proc Fun

I am fairly new to Ruby but I do have experience with Groovy so I have found learning and experimenting with Ruby somewhat of an easy effort. The Ruby community is pretty big so there are plenty of blog posts and other Web sites that are available, via a Google search, to help understand some problems when I get stuck. I started playing around with Ruby Proc (procedures), if/elsif/else and case/switch statements and here is what I am having fun with:

# define our apple Proc
apple = proc { |t| puts "my apple" + t }

Above we have our executable (proc) code assigned to the 'apple' variable.

# doIt1 with if statements
def doIt1(c, t)
  if t.respond_to?("call")
    puts "-- callable"
    c.call " is awesome"
    t.call " is really awesome"
  elsif t.kind_of?(Array)
    puts "-- not callable Array"
    t.each { |t1| c.call t1 }
  else
    puts "-- not callable String"
    c.call t
  end
end

Then we have a method 'doIt1(c,t)'. This method expects 2 arguments; the first argument, 'c', I expect is a Proc and the second argument, 't', I expect to be a Proc, Array or String.

if t.respond_to?("call")

The 'if' statement checks to see if 't' has a method named 'call' that it will respond to. I think the 'respond_to' method is great for dynamic languages. I could have just checked to see if 't' is a Proc as well, but then that limits me to one Object type, right?

t.kind_of?(Array)

The 'elsif' statement checks to see if 't' is of type Array. Like instanceof in Java.

# doIt2 with case/switch block
def doIt2(c, t)
  case t
    when Proc
      puts "-- callable"
      c.call " is awesome"
      t.call " is really awesome"
    when Array
      puts "-- not callable Array"
      t.each { |t1| c.call t1 }
    when String
      puts "-- not callable String"
      c.call t
    else
      puts "not valid"
    end
end

Then I created a method just like 'doIt1' called 'doIt2'. In 'doIt2', I used a case/switch statement and handled things similarly to 'doIt1'. In the second method, I check 't' to be of type String and have a default case for when 't' is not a Proc, Array or String.

# doIt1 tests
doIt1 apple, apple
doIt1 apple, " works good"
doIt1 apple, " works hard"
doIt1 apple, [" looks good", " looks elagant", " looks shiny"]

# *'s used to separate method tests
puts "*" * 40
puts "*" * 40

# doIt2 tests
doIt2 apple, apple
doIt2 apple, " works good"
doIt2 apple, " works hard"
doIt2 apple, [" looks good", " looks elagant", " looks shiny"]

Then I wrote a few 'tests' to see what would happen. Ruby is fun and I definitely enjoy working with Ruby and Groovy. Here is the full script file: appleProc.rb