PHP to Ruby on Rails Translations
Sunday, April 20th, 2008I used to develop primarily in PHP and dabbled into ASP but then I learned about Ruby and the Rails framework and now I cringe when I need to develop something new that isn’t in Ruby. There are a ton of tutorials on Rails so if you aren’t familiar or want to learn just do some googling. My intention with this post is to compare the differences in chunks of common code between php and ruby. Items such as for loops, array manipulation in ruby, various string functions in ruby and php, etc. I obviously won’t write everything so if you think of something that would be handy to know then leave a comment with it in there. Yes I realize PHP has frameworks that add some of the handy features that Rails.
Create Array:
Ruby: myArray = ["dog","cat","mouse"]
PHP: $myArray = array(”dog”,”cat”,”mouse”)
*With Ruby there’s no need to specify that it’s an array, it knows from the brackets. Also notice that PHP uses parentheses and Ruby uses brackets.
Using element of array by position
Ruby: myArray[1] = “cat”
PHP: $myArray(1) = “cat”
First Elements:
Ruby: myArray.first = “dog”
PHP: first($myArray) = “dog”
Ruby: myArray.first(2) = ["dog","cat"]
PHP: for ($i=0; $i < 1; $i++ ){$first2elements .= myArray($i);} * If there is a better way to do this in PHP let me know if it doesn’t involved a loop.
Print out elements of Array
Ruby: myArray.inspect
PHP: printr($myArray)
Comments
Ruby: # COMMENT
*Ruby doesn’t have multiline comments at the moment, just get a good editor that has a shortcut for it such as Textmate or Aptana.
PHP: // SINGLE LINE COMMENT
/* MULTILINE COMMENT */
Click to continue reading “PHP to Ruby on Rails Translations”


