Ruby From PHP

An introduction to Ruby for PHP Developers

Introduction

The guide was created for PHP developers wanting to transition to ruby as their main language or wanting another programming language to their toolkit. This is certainly not a programming language popularity contest. As a developer, its great to have the liberty to pick the best tool for the job. This tutorial will guide you through the Ruby way of doing things, using the PHP understanding that you already possess.

Ruby is A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. Ruby was created by Yukihiro Matsumoto (more affectionately known as Matz) in Japan starting in 1993

Basic assumptions

Before we get started, we are going to make the following assumptions:

  • You have PHP installed an running in your computer
  • You have a good understanding and working knowledge of the PHP language

Similarities between PHP and Ruby

As in PHP, in Ruby

  1. Ruby is dynamically typed, like in PHP, so you don’t need to worry about having to declare variables.
  2. There are classes, and you can control access to them like in PHP 5 (public, protected and private).
  3. Some variables start with $, like in PHP (but not all).
  4. There’s eval, too.
  5. You can use string interpolation. Instead of doing "$foo is a $bar", you can do "#{foo} is a #{bar}"—like in PHP, this doesn’t apply for single-quoted strings.
  6. There’s heredocs.
  7. Ruby has exceptions, like PHP 5.
  8. There’s a fairly large standard library.
  9. Arrays and hashes work like expected, if you exchange array() for { and }: array('a' => 'b') becomes {'a' => 'b'}.
  10. true and false behave like in PHP, but null is called nil.

Differences between PHP and Ruby

  1. There’s strong typing. You’ll need to call to_s, to_i etc. to convert between strings, integers and so on, instead of relying on the language to do it.
  2. Strings, numbers, arrays, hashes, etc. are objects. Instead of calling abs(-1) it’s -1.abs.
  3. Parentheses are optional in method calls, except to clarify which parameters go to which method calls.
  4. Instead of naming conventions, like underscores, the standard library and extensions are organized in modules and classes.
  5. Reflection is an inherent capability of objects, you don’t need to use Reflection classes like in PHP 5.
  6. Variables are references.
  7. There’s no abstract classes or interfaces.
  8. Hashes and arrays are not interchangeable.
  9. Only false and nil are false: 0, array() and "" are all true in conditionals.
  10. Almost everything is a method call, even raise (throw in PHP).

Installation

Variables

Declaring variable in php

  • $var could be a local variable.
  • @this->var is an instance variable.
  • $GLOBALS['var'] is a global variable

Declaring variable in ruby

  • var could be a local variable.
  • @var is an instance variable.
  • $var is a global variable
        
          
          #--------------------------
          # Local variables
          #--------------------------
          
          $a= 1;
          $b = 2;
          print "---------\n[php]\n\n";
          print "Add local vals:".($a+$b)."\n"

          #--------------------------
          # Class and instance variables
          #--------------------------

          class Foo
          {
            function __construct()
            {
              $this.a = 'A'
              echo "Doing foo."; 
            }

            function print_a()
            {
              echo "Varibale A :". $this->a; 
            }

            function get_a()
            {
              return $this->a; 
            }

          }

          $foo = new Foo();
          $foo->print_a();
        
      
          
          
          #--------------------------
          # Local variables
          #--------------------------
          
          a= 1
          b = 2
          puts "---------\n[ruby]\n\n"
          puts "Add local vals: #{$a+$b} \n"
         
          #--------------------------
          # Class and instance variables
          #--------------------------

          class Foo
            def initialize
              @a = 'A'
              echo "Doing foo."; 
            end

            def print_a()
              echo "Varibale A : #{@a}"
            end

            def get_a()
              @a
            end

          end

          foo = Foo.new
          foo.print_a()
        
      

Methods

        
          
          #--------------------------
          # Simple PHP function
          #--------------------------
          
          function a_function($arg, $arg)
          {

          }
        
      
        
          
          #--------------------------
          # Simple Ruby function
          #--------------------------
          
          def a_function(arg, arg)
          end

        
      

Strings and symbols

In Ruby a string is defined as a quote (") followed by zero or more letters, numbers, or symbols and followed by another quote ("). Some simple strings would be "hello" or "This sentence is a string!". Strings can be anything from "", the empty string, to really long sets of text.

Symbols are difficult to explain. You can recognize a symbol because it starts with a colon then one or more letters, like :flag or :best_friend.

PHP has no concept of symbols

        
          
          #--------------------------
          # PHP strings
          #--------------------------
          
          $string = 'this is a simple string';
          // Outputs: Arnold once said: "I'll be back"
          $string2 = echo 'Arnold once said: "I\'ll be back"';         

        
      
        
          
          #--------------------------
          # Ruby strings
          #--------------------------
          
          string = "this is a simple string"
          string2 = echo 'Arnold once said: "I\'ll be back"';  
        
      

Collections (Arrays and Hashes)

        
          
          #--------------------------
          # PHP Arrays 
          #--------------------------
          

          $array = array(
              "foo" => "bar",
              "bar" => "foo",
          );

          // as of PHP 5.4
          $array = [
              "foo" => "bar",
              "bar" => "foo",
          ];

          $array = array("foo", "bar", "hello", "world");

        
      
        
          
          #--------------------------
          # Ruby array
          #--------------------------
          
          meals = ["breakfast","lunch","dinner"]

          
          #--------------------------
          # Ruby Hashes
          #--------------------------
          
          produce = {"apples" => 3, "oranges" => 1, "carrots" => 12}
          produce = {apples: 3, oranges: 1, carrots: 12}

        
      

Conditionals

        
          
          #--------------------------
          # comment
          #--------------------------
          
          $age = 25;
          if($age < 40){
             echo "young lad";
          }
          else{
              echo "Old bugger";
          }
        
      
        
          
          #--------------------------
          # comment
          #--------------------------
          
          age = 25
          if age < 25
             puts "Young lad"
          else
             puts "Old bugger"
          end