RubyLearning

Helping Ruby Programmers become Awesome!

Course Ruby Programs

By Satish Talim

Here are all the programs that we would be discussing while learning Ruby at rubylearning.github.io.

# p001hello.rb
=begin
  Ruby is an interpreted language
  Source file has .rb extension
  Free format and case sensitive
  No statement delimiters
  Two types of comments
  String literals in single or double quotes
=end
puts 'Hello'
# p002rubynumbers.rb
=begin
 Ruby Numbers
 Usual operators:
 + addition
 - subtraction
 * multiplication
 / division
=end

puts 1 + 2
puts 2 * 3
# Integer division
# When you do arithmetic with integers, you'll get integer answers
puts 3 / 2
puts 10 - 11
puts 1.5 / 2.6
# class hierarchy
# http://www.cs.mun.ca/~donald/slug/2003-10-16/presentation/img5.html
# p003rubystrings.rb
=begin
  Ruby Strings
  In Ruby, strings are mutable
=end

puts "Hello World"
# Can use " or ' for Strings, but ' is more efficient
puts 'Hello World'
# String concatenation
puts 'I like' + ' Ruby'
# Escape sequence
puts 'It\'s my Ruby'
# New here, displays the string three times
puts 'Hello' * 3
# Defining a constant
# More on Constants later, here
# /satishtalim/ruby_names.html
PI = 3.1416
puts PI
# p004stringusage.rb
# Defining a constant
PI = 3.1416
puts PI
# Defining a local variable
my_string = 'I love my city, Pune'
puts my_string
=begin
  Conversions
  .to_i, .to_f, .to_s
=end
var1 = 5;
var2 = '2'
puts var1 + var2.to_i
# << appending to a string
a = 'hello '
a<<'world.
I love this world...'
puts a

=begin
  << marks the start of the string literal and
  is followed by a delimiter of your choice.
  The string literal then starts from the next
  new line and finishes when the delimiter is
  repeated again on a line on its own.
=end
a = <<END_STR
This is the string
And a second line
END_STR
puts a
# p005methods.rb
# gets and chomp
puts "In which city do you stay?"
# STDOUT - global constant - the actual standard output stream for the program
# flush - flushes any buffered data within io to the underlying operating system
STDOUT.flush
# gets - returns a string and a '\n' character
# chomp - removes this '\n'
city = gets.chomp
puts "The city is " + city

# to know which object you are in
puts self
# p006ftoc.rb
puts 'Enter temperature in Fahrenheit: '
STDOUT.flush
temp_in_fahrenheit = gets.chomp
temp_in_celsius = (((temp_in_fahrenheit.to_f - 32.0) / 9.0) * 5.0)
puts 'Temperature ' + temp_in_fahrenheit + ' degree Fahrenheit = ' + format("%.2f", temp_in_celsius) + ' degree Celsius'
# p007dt.rb
=begin
  The first character of a name helps Ruby to distinguish its intended use
  instance variable name starts with a @ sign
  class variable name starts with a @@ sign
  global variable name starts with a $ sign
  constant name starts with an uppercase letter
  Method names should begin with a lowercase letter
  ?, ! and = are the only weird characters allowed as method name suffixes
  ! or bang labels a method as dangerous-specifically
  use underscores to separate words in a multiword method or variable name
  Class names, module names and constants use capitalization
=end

# Ruby is dynamic
x = 7           # integer
x = "house"  # string
x = 7.5        # real

# In Ruby, everything you manipulate is an object
'I love Ruby'.length
# p008mymethods.rb
# A method returns the value of the last statement
# Methods that act as queries are often named with a trailing ?
# Methods that are "dangerous," or modify the receiver, might be named with a trailing ! (Bang methods)
# A simple method
def hello
  'Hello'
end
#use the method
puts hello

# Method with an argument - 1
def hello1(name)
  'Hello ' + name
end
puts(hello1('satish'))

# Method with an argument - 2
def hello2 name2
   'Hello ' + name2
end
puts(hello2 'talim')
# p009mymethods1.rb
# interpolation refers to the process of inserting the result of an
# expression into a string literal
# the interpolation operator #{...} gets calculated separately
def mtd(arg1="Dibya", arg2="Shashank", arg3="Shashank")
  "#{arg1}, #{arg2}, #{arg3}."
end
puts mtd
puts mtd("ruby")
# p029dog.rb
# define class Dog
class Dog
  def initialize(breed, name)
    # Instance variables
    @breed = breed
    @name = name
  end

  def bark
    puts 'Ruff! Ruff!'
  end

  def display
    puts "I am of #{@breed} breed and my name is #{@name}"
  end
end

=begin
  Classes in Ruby are first-class objects - each is an instance of class Class.
  When a new class is defined (typically using class Name ... end), an object of
  type Class is created and assigned to a constant (Name. in this case).
  When Name.new is called to create a new object, the new instance method in Class
  is run by default, which in turn invokes allocate to allocate memory for the object,
  before finally calling the new object's initialize method. The constructing and
  initializing phases of an object are separate and both can be over-ridden.
  The initialization is done via the initialize instance method while the construction
  is done via the new class method. initialize is not a constructor!
  Class Hierarchy - http://www.cs.mun.ca/%7Edonald/slug/2003-10-16/presentation/img5.html
=end

# make an object
# Objects are created on the heap
d = Dog.new('Labrador', 'Benzy')

=begin
  Every object is "born" with certain innate abilities.
  To see a list of innate methods, you can call the methods
  method (and throw in a sort operation, to make it
  easier to browse visually)
=end
puts d.methods.sort

# Amongst these many methods, the methods object_id and respond_to? are important.
# Every object in Ruby has a unique id number associated with it
puts "The id of obj is #{d.object_id}."

# To know whether the object knows how to handle the message you want
# to send it, by using the respond_to? method.
if d.respond_to?("talk")
  d.talk
else
  puts "Sorry, the object doesn't understand the 'talk' message."
end

d.bark
d.display

# making d and d1 point to the same object
d1 = d
d1.display

# making d a nil reference, meaning it does not refer to anything
d = nil
d.display

# If I now say
d1 = nil
# then the Dog object is abandoned and eligible for Garbage Collection (GC)
=begin
  The Ruby object heap allocates a minimum of 8 megabytes.
  Ruby's GC is called mark-and-sweep. The "mark" stage checks objects
  to see if they are still in use. If an object is in a variable that
  can still be used in the current scope, the object (and any object
  inside that object) is marked for keeping. If the variable is long gone,
  off in another method, the object isn't marked. The "sweep" stage then
  frees objects which haven't been marked.
  If you stuff something in an array and you happen to keep that array around,
  it's all marked. If you stuff something in a constant or global variable,
  it's forever marked.
=end

This page shows selected Ruby programs from the course. More examples are available throughout the tutorial sections.