Lazycoder

25Feb/051

new adventures in Ruby part two

How bizzare. In Ruby you can use conditionals in your return statements. I’m adding an indexer to a class called “Blog”. This is used to retrieve the entries. If an integer key is passed in, the entry is retrieved from the array by using the integer index. If it’s anything else, it calls the getEntry method.

	def [] (key)
		return @entries[key] if key.kind_Of?(Integer)
		return getEntry(key)
	end

	def getEntry(id)
		return @entries.find { |aEntry| aEntry.id == id }
	end

It looks like it compiles, but will it do what I want it to do? We’ll find out.

Here is what the Blog class looks like right now.

class Blog
	attr_reader :name, :author, :entries
	attr_writer :entries

	def initialize(name, author)
		@name = name
		@author = author
		@entries = Array.new
	end

	#returns the title of the blog which is the name + "by" + author
	def title
		return @name + " by " + @author
	end

	def addEntry(entry)
		@entries.push(entry)
	end

	def [] (key)
		return @entries[key] if key.kind_Of?(Integer)
		return getEntry(key)
	end

	def getEntry(id)
		return @entries.find { |aEntry| aEntry.id == id }
	end
end

I wrote a short script to test out my new Blog class.

#!/sw/bin/ruby
require 'cgi'
require 'blog.rb'
theBlog = Blog.new("My Blog","Me")
cgi = CGI.new("html4")
cgi.out{
cgi.html{
	cgi.head{"\n"+cgi.title{"This is a test"} } +
	cgi.body{"\n" + theBlog.title
	}
}
}

First I called the rub syntax checker (ruby -c filename) to make sure I had everything correct. When I loaded the page in the browser I was presented with the text “My Blog by Me” at the top of the page. Great!

  • http://dougal.gunters.org/ Dougal Campbell

    You can do post-conditional notation like that in Perl, too. These are pretty common constructs in perl:

    ## Same as: if ($good) do_something();
    do_something() if $good;

    ## Same as: if (! $bad) do_something();
    do_something() unless $bad;

    I’ve been keeping my eye on Ruby on Rails for a while now. I just wish I had time to play with it, myself.

  • Pingback: entry key