Man

Development & AI | Alper Akgun

Ruby by example

September, 2023

Ruby examples


# watch ruby rb1.rb  # this runs the examples

PI = 3.14159 # constanst
name = "Alice"
lastname = 'Wonderlander' # single quotes
story = < 9,
  "rabbits" => 10,
}

print("Welcome\n")
puts "PI=#P{PI}, likes=#{likes}"

# arrays
countries = [
  "Sweden",
  "Norway",
  "Finland",
]

puts(countries[2])
puts countries[0..1]
puts countries[2..-1]
countries << "Turkey"
puts countries.inspect

likes = [["Turkey", "Ankara"], ["France", "Paris"]]
puts likes.inspect

puts likes.to_h

# hashes
capitals = {"Turkey"=>"Ankara", "France"=>"Paris"}
capitals = { Turkey: :ankara, France: :paris} # symbols
puts capitals.inspect


# functional
puts countries.map(&:upcase)
countries.each do |country|
  puts country.downcase
end

puts countries.select { |c| c.start_with?('F') }
puts countries.join(', ')
puts countries.inject("Hey: ") { |s, v| "#{s}-#{v}"}

# hash
puts capitals.keys
puts capitals.values
puts capitals.select { |k, v| v.to_s.start_with?("a") }

# symbols

puts :my_symbol, :my_symbol.to_s, "my_symbol".to_sym, "my_symbol".intern


# methods

def area_of_circle(radius)
  PI * radius ** 2
end

puts area_of_circle(2)

def greet(name, greet="Hello:", *args, **kwargs)
  puts greet, name, args.inspect, kwargs.inspect
end

greet("Alice", "Yo", 1, 2, 3, x: 4, y: 5)


# classes

class Circle
  @radius = 0

  attr_reader :radius
  attr_writer :radius
  # attr_accessor :radius

  def initialize(r)
    @radius = r
  end

  def area_of_circle
    Math::PI * @radius * @radius
  end

  private

  def foo
    return 2
  end

  def bar
    "bar"
  end
end

c = Circle.new(10)
puts c.area_of_circle


class Shape
  def initialize
  end
end

class Square < Shape
  @side = 0
  def initialize(s)
    super()
    @side = s
  end
end

puts Square.new(1).class.ancestors.inspect


# Modules

module HeyMod
  def grrr
    puts "grrr"
  end
end

require 'date' # require external modules
puts Date.today

module Action
  include HeyMod
end

class Cat
  include Action
end

puts Cat.new.grrr


# Blocks, lambdas

def doit
  yield
end

puts doit { print "Why\n" }

quatro = Proc.new {|x| x ** 4 }
puts [*1..5].map(&quatro).inspect


mult3 = lambda { |x| x * 3 }
puts mult3.call(2)

=begin
  multiline comments
=end

puts (3 ** 3) / 3 * 5 + 1 - 4

# Conditionals

if 3 > 11
  puts true
elsif false == ''
  puts false
else
  puts "Why"
end

puts "unless" unless false

case PI
when 3.14159
  puts "3.14159"
when true
  puts true
else
  puts "else"
end


puts !((true && false) || true)

"1".to_i
"test".to_sym
"test".intern
:test.to_s
"Hey".downcase
"hey".capitalize
"Hey".include? "i"
"Hey".gsub!(/e/, "o")
"Hey".length
"Hey".reverse
"Hey".upcase

# loops

i = 0
while i < 10
  puts i
  i+=1
end

i = 0
until i == 6
  puts i.to_s.inspect
  i += 1
end


for i in 1..3
  puts i
end

i = 1
loop do
  i *= 3
  next if i == 27
  puts i
  break if i > 125
end