As I'm just learning Ruby, I sometimes need to jog my memory. Perhaps this will be useful to others, too. See the manual or the book for more detail.

Other references

Variables and constants

FOO    # constant
$foo   # global
@@foo  # class
@foo   # instance
foo    # local

Arrays

a = [ 1, 'cat', 3.14 ]   # array with three elements
a = [*x]                 # converts object 'x' to array
a = [*1..5]              # creates an array filled with the numbers of the range: [1,2,3,4,5]

ref on [*x] syntax

Classes

declaration:

class Foo < Super
   BAR = "bar"

   def initialize(name)  # constructor
      @name = name
   end

   def method0
      return @name
   end

   def method1 (arg1)
      super arg1
      print arg1
   end

   def Foo.classMethod arg1
      return arg1 * arg1
   end

   protected
   def protected1
      print "protected method"
   end

   private
   def private1
      print "private method"
   end
end

access:

myvar = Foo::BAR    # access constant BAR in class Foo
myinstance = Foo.new "myname"
whatismyname = myinstance.method0

hints and tools

telling the difference between a string and an array

An array will return true for var.respond_to?("join")


CategoryCheatSheet

iDIAcomputing: RubyCheatSheet (last edited 2009-07-27 18:25:13 by localhost)