Ruby for the PHP Programmer ...

This will be a series of my findings in the syntax and language of Ruby from a PHP perspective.

Displaying and formatting output is one of the first things you need to know when learning a new language.


echo Look it up at
echo value [,values];
This is not a function, so ( ) is not needed. It is a language construct. Hmm, something I just learned. it will concat the variable for you and display. This might come in handy, sometimes is a pain to always do print $var1 . " " . $var2; Sometimes those periods are easy to forget!


$first = "Nola";
$last = "Stowe";
echo $first, ' ', $last, "<br>";

print Look it up at
print value;
Also not a function but a language construct, so () not needed here as well.


$first = "Nola";
$last = "Stowe";
print $first." ". $last."<br>";
// or
print "$first $last <br>"";

results in:
Nola Stowe

For more on the differences of print and echo, read:

In most cases, I usually use print.

Also availble in php, but I never rarely use:
printf (string format, [, mixed args]); uses a formatting string
sprintf (formats as printf, but reutrns a string rather than printing)
vsprintf (like sprintf, but accepts an array of values instead of a variable number)
vprintf (like printf, but accepts an array of values instead of a variable number)

(which BTW, does not require ; at end of line, local vars don't have $ those are reserved for globals)

first = "Nola"
last = "Stowe"

print first, ' ', last, "<br>"

prints contents of variable test followed by test2

results in:
Nola Stowe

However, it appears some special variables (lookie! a $!!! that means they are global)

$, = " " #displayed between variables in print
$\ = "<br>" #displayed at end of the line

Will set some defaults for the print statement, so once those are set, all you need to do is:

print first,last

To get the same result. Cool, huh?

Also in Ruby I found puts, and putc. I need to do some more investigation on those. Perhaps a reader can shed some light?

So you can see, PHP's echo is most like Ruby's print. That should help us die hard php programmers who normally use print exclusively.
Also in Ruby, which seem to work like the php versions:

Thanks for the Ruby Tips Florian!!

Thanks! I wasn't sure what "p" did and the usefulness of $/ and $, ...I could see how that could make the code hard to read. Thanks for the example about string interpolation, I was wondering how you could put variables and text in the same line and have the variables replaced.