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!



Pingback: entry key