Poking around in Ruby

Ruby for Windows (I'm not sure if other operating systems have similar, but I would think so) has a program called "fxri - Interactive Ruby Console and Help." This little application consists of a frameset with one panel as a documentation browser, one panel to display the help for the currently selected item and an interactive console. This can be a great aid in learning ruby and for testing out functions or code. Here I'll talk about a few things I've learned with this.

You get a prompt as you would with an operating system, looks something like this:
irb(main):001:0>

puts (obj, … )
Writes given object to ios, with record separate after each element, if given an array each element is put with a record separator.

example

First, I'll declare a as an Array with these elements

irb(main):002:0> a = ["apple", "orange", "banana"] Enter
=> ["apple", "orange", "banana"]

Then print the array

irb(main):003:0> puts a Enter
apple
orange
banana
=> nil

(the => nill indicates what puts functions return value might be, in the case of defining an array it returns the value of an array. The puts function returns nil)

Then I wondered, what exactly does "p" do in comparison?

irb(main):004:0> p a Enter
["apple", "orange", "banana"]
=> nil

It prints the contents of the object, in this case an array. Nice for debugging. I think I elaborated more about displaying output in a previous blog entry.

How do these two handle a simple string?

First, lets define a string:
rb(main):005:0> s = "this is a string" Enter
=> "this is a string"

irb(main):006:0> p s
"this is a string"
=> nil

irb(main):007:0> puts s
this is a string
=> nil

As you can see, the p prints it as a quoted string, whereas puts displays the value. See how using this interactive consol can help you in times where you might forget exactly what each function does and wonder if you can just test it out and see. Looking up in the docs is fine sometimes, but some things I'd rather just try out. You wouldn't believe how many times I've edited my test.php file, removed what I had in there before and put a little code in to test (I have recently seen some php consoles, but I have yet to investigate).

Upon further investigation on the "p" function, the documentation says it calls the object.inspect method, which returns a string containing a human-readable representation of object. If not overridden, it uses the objects to_s method to generate the string. Interesting. So if you'd like to capture this as a string you can use obj.inspect instead of p obj …….. Nifty.

The only thing I wish the docs has was a "see also" section for related commands.

Give it a shot and report back what you learned :)