Ruby in More Than 20 Lines

First 20 Minutes

Heavily inspired by Ruby in Twenty Minutes

class Greeter
def initialize(name = "World")
     @name = name.capitalize
   end
   def say_hi
     puts "Hello #{@name}!"
   end
   def give_num
     puts "Give me #{Math.sqrt(9)} years"
   end
 end
g = Greeter.new
g.say_hi
Greeter.instance_methods
Greeter.instance_methods(false)
g.respond_to?("name")
g.respond_to?("to_S")

class Greeter
  attr_accessor :name # def 2 methods: `name` get, `name=` set
end
#!/usr/bin/env ruby

class MegaGreeter
  attr_accessor :names

  # Create the object
  def initialize(names = "World")
    @names = names
  end

  # Say hi to everybody
  def say_hi
    case
    when !@greeted
      if @names.nil?
        puts "You Are Nameless"
      elsif @names.respond_to?("each")
        # @names is a list of some kind, iterate!
        # between do…end is a block of code to run, like a lambda
        # |parameter|
        @names.each do |name|
          puts "Hello #{name}!"
        end
      else
        puts "Hello #{@names}!"
      end
      greet
    else
      say_bye
    end
  end

  # Say bye to everybody
  def say_bye
    if @names.nil?
      puts "No one exists"
    elsif @names.respond_to?("join")
      # Join the list elements with commas
      puts "Goodbye #{@names.join(", ")}.  Come back soon!"
    else
      puts "Goodbye #{@names}.  Come back soon!"
    end
  end

  private
  def greet
    @greeted ||= true
  end
end

if __FILE__ == $0 # allow this file to be a library, not the main
  mg = MegaGreeter.new
  mg.say_hi
  mg.say_bye

  # Change name to be "Zeke"
  mg.names = "Zeke"
  mg.say_hi
  mg.say_bye

  # Change the name to an array of names
  mg.names = ["A", "B", "C",
              "D", "E"]
  mg.say_hi
  mg.say_bye

  # Change to nil
  mg.names = nil
  mg.say_hi
  mg.say_bye
end

Different Outputting

puts

  • to_s
  • newline
  • white space for nil
  • prints array element line by line
  • always return nil
  • doc

print

  • to_s
  • no newline
  • prints nothing for nil
  • prints array as a whole thing
  • always return nil
  • behavior are affected by variables
  • doc

p

  • inspect
  • newline
  • debugging
  • doc

Arguments

def func(a, b = "B", aa, *sp, c: "C", d:, **ksp, &callback)
end

Long String Formatting

p 'a string using '\
  'implicit concatenation'

p <<SOME_END.gsub(/\s+/," ").strip
a string using
HEREDOC syntax
printing another str: #{s}
SOME_END

p <<"SOME_END".gsub(/\s+/," ").strip
a string using
HEREDOC syntax
printing another str: #{s}
SOME_END

p <<`SOME_END`.gsub(/\s+/," ").strip
echo "a command using HEREDOC syntax"
SOME_END

p(<<"FIR", 123, <<"SEC")
This is the first str
FIR
This is the second str
SEC

p <<-SOME_INDENTED_END.gsub(/\s+/," ").strip
  this is
  indented
  SOME_INDENTED_END

p %{
SELECT * FROM     food
         GROUP BY food.type
}.gsub(/\s+/, " ").strip

Percent Strings

Percent Strings

For strings, an uppercase letter allows interpolation and escaped characters while a lowercase letter disables them.

Most non-alphanumeric characters can be used as delimiters, like (), |, %, <>, {}…

Note the brackets must be paired if used.

# strings
%()
%q(string)
%Q(string with interpolation and escaped char)
%w(array of strings) # need to escape space (\ ) if space in strings
%W(array of strings with interpolation and escaped char)
%w(word1 word2 word3 I\ am\ a\ word) # example of w

%s(symbol)
%i(array of symbols)

%r(regular expression)

%x(shell command, ``)

%^I'm another string #{puts "printing"}^