מבוא לשפת Ruby


תוכנית רובי ראשונה - שלום עולם:

# This is my first ruby program
# A ruby program is written line after line
# (much like many other scripting languages)
#
# The parenthesis are optional when calling a function,
# so both of these lines do the same thing:
puts "Hello World"
puts("Hello WOrld")

# puts prints a text line to the terminal and appends a newline
# print does the same but doesn't add the newline
print "Hello. Who are you?"

# gets reads a line of input from stdin
name = gets

# ruby supports string interpolation using #{...} syntax
print "Wow nice to meet you #{name} - #{1 + 1}"

תוכנית רובי שניה - חישוב ההפרש בכל שורה בין הערך הגדול ביותר לקטן ביותר, ואז סיכום כל ההפרשים:

# A variable in ruby is declared automatically
# when it is first assigned to
res = 0

# File.open returns a file object,
# and file objects have a method called 'each_line'
# so the following code opens the file AND calls each_line
# on the resulting file object.
#
# The method each_line takes a block as input
# and will call the block (using yield) on every
# line in the file. Passing blocks around is the main
# way in ruby to implement iterations.
File.open('input.txt').each_line do |line|
  # The method String#split takes a string and splits it to an array
  # The method Array#map takes an array and a method and invokes the method
  # on each element in the array (returning an array of the results)
  # Chaining method calls like this looks really nice because no parenthesis are needed.
  data = line.split.map(&:to_i)

  # Ruby's philosophy is to provide as many built-in methods as possible
  # so developers never need to implement infrastructure code.
  # That's why we have Array#max, Array#min and many others.
  res += data.max - data.min
end

puts res

פקודות תנאי:

# Read an input line from the user
name = gets

# Strings can be accessed using the brackets
# operator, so here we check if the first character was A
if name[0] == 'A'
  puts "WElcome master"
else
  puts "bye bye..."
end

לולאות ב Ruby:

# The keyword def defines a function
# The return is optional as well as the parenthesis in the
# function header
# A function definition ends with the "end" keyword
def twice(x)
  return x * 2
end

# The syntax do ... end defines a block
# blocks represent code that is sent to other functions
# The function Integer#times takes a block and calls it
# n times (according to the integer value)
10.times do |val|
  puts "Hello #{val}"
end

# A while loop also works just like in other languages
x = 5
while x < 10
  x += 1
  puts twice(x)
end


בלוקים ופונקציות:

# The command yield invokes the block passed
# to this function
def call_twice
  yield
  yield
end

# So for example to function Integer#times looks
# something like the following:
def call_n_times(n)
  i = 0
  while i < n
    yield
    i += 1
  end
end

# Calling that function works just the same as calling
# built-in functions that take blocks
call_n_times(10) do
  puts "Hello World"
end

מימוש מחלקה ב Ruby:

# The class keyword defines a class
# The class definition ends with the "end" keyword
class Person
  # In ruby we can actually write code here inside the class
  # definition. Code written here has access to its containing class
  # and so many times it is used to modify the class definition
  # dynamically. For example the function attr_accessor is used
  # to add getter and setter methods to the class automatically

  # attr_accessor :name
  # attr_reader :name
  # attr_writer :name

  # A special method `initialize` is called every time
  # a new object from this class is generated (with new)
  # Ruby marks member fields with the special @ prefix
  # so our person class has one member data variable called @name
  def initialize(name)
    @name = name
  end

  # getter
  def name
    @name
  end

  # setter
  def name=(val)
    @name = val
  end

  def say_hi
    puts "#{@name} - Hello"
  end
end

p = Person.new('ynon')
q = Person.new('ynon')
r = Person.new('ynon')

p.name = 'demo'
puts p.name

קל מאוד ב Ruby לשנות קוד קיים של המערכת באמצעות Monkey Patching:

# Monkey patching is the ability to change built-in
# language behaviour by extending the classes.
# Here for example we change the Integer class by
# overriding its #to_s method
class Integer
  def to_s
    'Hahaha'
  end
end

# Another example - adding Array#second, Array#third
# to all the arrays in ruby
class Array
  def first
    self[0]
  end

  def second
    self[1]
  end

  def third
    self[2]
  end
end