Ruby: Learn Ruby in 1 Hour
This is a Ruby tutorial. I assume you already know a scripting language. (e.g. Python, JavaScript, etc) This intro is designed to quickly get you started. After reading, you should be able to use standard documentation.
Ruby has a interactive command line. In terminal, type irb
This tutorial is based on Ruby 3. [see Ruby Version Release Dates]
Printing
Strings
Numbers and String Conversion
Everything is a Object; Finding Object's Methods
Variables
True, False
Conditional: if then else
Loop, Iteration
Array (List)
Hash Table
Call Shell Command
Defining a Function
Classes and Objects
Defining a class. Class name should start with a capital letter.
# ruby # Object example class Xyz # initializer def initialize(ii) @xx = ii # @xx is a instance variable end # a method. Return the instance variable @xx def mm @xx end # a another method. def nn(aa) @xx + aa end end # create a object. myobj = Xyz.new(3) # call a method p myobj.mm # 3 # call another method with argument p myobj.nn(2) # 5
Instance variable must be accessed by methods only. You must define methods to get instance variable's value, or change it. (this is different from Java or Python.)
- “Instance Variable” are variables such that each object has a different copy. Changing one variable in one object doesn't change that variable's value in another object. Name of instance variables must start with
@
. - “Class Variable” are variables such that all objects share one single copy of the variable. Name of class variables must start with
@@
.
Writing a Module
# ruby # Module name must start with Capital letter module Xyz # … end