Home‎ > ‎Comp‎ > ‎Ruby‎ > ‎

Syntax

puts "Hello World, 3+2=#{3+2}" # puts=put screen; technically short for self.puts
puts "9/2=#{9/2}=4, whereas 9.0/2=#{9.0/2}=4.5"+"!"*3
3+2;3*2;3**2;Math.sqrt(9) # 3
a=3**2; b=4**2;Math.sqrt(a+b) # 5
def h
    puts "Hello World!"
end
h # Hello World
h() # Hello World

def h(name) # with argument
    puts "Hello #{name}" # string substitution with #{...}
end
h("Chris")

def h(name="World") # ie default name
    puts "Hello #{name.capitalize}!"
end
h "chris" # Hello Chris!
h # Hello World!
class Greeter
    def initialize(name="World")
        @name=name # instance variable
    end
    def say_hi
        puts "Hi #{@name}!"
    end
    def say_bye
        puts "Bye #{@name}!"
    end
end
g=Greeter.new("Pat")
g.say_hi # Hi Pat!
g.say_bye # Bye Pat!
Greeter.instance_methods # ["method", "send", "object_id", ...]
Greeter.instance_methods(false) # ["say_bye", "say_hi"]
g.respond_to?("name") # false
g.respond_to?("say_hi") # true
g.respond_to?("to_s") # true
class Greeter
    attr_accessor :name
end
g.respond_to?("name") # true
g.name # Pat
g.name="Betty"
g.say_hi # Hi Betty!

#!/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
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("each")

      # @names is a list of some kind, iterate!
      @names.each do |name|
        puts "Hello #{name}!"
      end
    else
      puts "Hello #{@names}!"
    end
  end

  # Say bye to everybody
  def say_bye
    if @names.nil?
      puts "..."
    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
end


if __FILE__ == $0
  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 = ["Albert", "Brenda", "Charles",
    "Dave", "Englebert"]
  mg.say_hi
  mg.say_bye

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

 
 
#!/usr/bin/ruby
# may have to chmod 755 basic.rb (in order to grant access)

print "Enter your name:"
name=gets.chomp
puts "name.length=#{name.length}"
require "date"
d=DateTime.now
puts "Today's date=#{d.year}/#{d.month}/#{d.day}"
puts '\'string\'.reverse='+'string'.reverse
puts '\'High\'.upcase='+'High'.upcase
puts '\'High\'.downcase='+'High'.downcase
puts '\'High\'.swapcase='+'High'.swapcase
puts '\'johnny\'.capitalize='+'johnny'.capitalize
lineWidth=50
puts 'center'.center(lineWidth)
puts 'still in center'.center(lineWidth)
puts 'and even still in center'.center(lineWidth)
puts '\'me\'.ljust(50)'.ljust(lineWidth)
puts '\'me\'.rjust(lineWidth)'.rjust(lineWidth)
puts '5**2='+(5**2).to_s
puts '10%3='+(10%3).to_s
puts '(2-5).abs='+(2-5).abs.to_s
puts 'rand='
puts rand
puts 'rand(100)='+rand(100).to_s+' (would give you any number between 0 and 99!)'
puts 'Math::PI='+Math::PI.to_s
puts '< > <= >= == !='
r=rand(2)
if r==1
puts r.to_s+': odd number'
else
puts r.to_s+': even number'
end

result = ''
while result != '7' and result != '6' and result != '8'
puts 'What is 3+4 (you may be incorrect by 1)?'
result = gets.chomp
end
if result=='7'
puts 'Very good.'
else
puts 'Near enough.'
end

puts '====== ARRAYS ============'
fruit = ['apple','pear','melon']
puts fruit
puts 'puts fruit.to_s'
puts fruit.to_s
puts 'puts fruit.join(', ')'
puts fruit.join(', ')
puts 'puts fruit.last'
puts fruit.last
puts 'puts fruit[0]'
puts fruit[0]
puts 'puts fruit.push(\'push\')'
puts fruit.push('push')
puts 'puts fruit.pop'
puts fruit.pop

puts '============ CLASSES =============='
class Die
    def initialize
        roll
    end
    def roll
        @numberShowing = 1 + rand(6)
    end
    def showing
        @numberShowing
    end
end


result = Die.new.showing
puts 'Your die has rolled: ' + result.to_s
puts 'Not a 6 this time...' if result < 6
puts '=============== PROGRAMMING RUBY ================================'
# ==begin
a = %w{ apple pear banana }
puts a
puts 'LOOPING CONSTRUCTS:'
5.times { print '*' }
3.upto(6) { |i| puts i.to_s+'**2='+(i**2).to_s }
### {'a'..'e'}.each { |char| print char }

# www.ruby-lang.org/en/documentation/quickstart
def h(name="World")
puts "Hello #{name}!"
end

h("AJ")
puts '============== CLASS ===================='

puts '===== www.rubyist.net/~slagell/ruby =========='
word="fo"+"o"
puts word*=2
puts word
puts word[0] # 102 = ASCII of 'f'
puts word[-1] # 111 = ASCII of 'o'; -1 = offset from the END
herb="parsley"
puts 'herb: '+herb
puts 'herb[-3,2]: '+herb[-3,2] # le
puts 'herb[2..4]: '+herb[2..4] # rsl

ary=[1,2,"3"]
ary+["foo","bar"] # [1,2,"3","foo","bar"]
puts 'ary*2: '
puts ary*2 # [1,2,"3",1,2,"3"]

puts "Some words" # implicit newline
print "Some words\n" # newline must be given for print
print "Some words","\n" # concatenate with comma

s1="abc"
s2=s1.chop
s1.chop! #ab : "bang" actually alters s1 (in contrast to s1.chop)
puts s2 # ab
puts s1 # ab

puts "========== case =============="
print "Enter a number between 1 and 10: "
i=gets.chomp
case i
when 1, 2..5
    puts "1..5"
when 6..10
    puts "6..10"
end
i=8
puts i+=1 while i<15

for num in 4..6
    puts num
end

for elt in [100,-9.6,"pickle"]
    puts "#{elt}\t(#{elt.class})"
end

"abc".each_byte{|c| printf "<%c>", c}; print "\n" # <a><b><c>
"a\nb\nc".each_line{|l| print l};print "\n"

def repeat(num)
    while num>0
        yield # ie executes the block passed to 'repeat'
        num -= 1
    end
end
repeat(3) { puts "foo" }

#========== INHERITANCE =================
class Mammal
    def breathe
        puts "inhale and exhale"
    end
end
class Cat<Mammal
    def speak
        puts "Meow"
    end
end
tama=Cat.new
tama.breathe # inhale and exhale
tama.speak # Meow

#===================================================
class Bird
    def preen
        puts "I'm cleaning my feathers"
    end
    def fly
        puts "I can fly"
    end
end
#====== SUBSEQUENT CHANGE TO INHERITED METHOD =======
class Penguin
    def fly
        fail "Sorry. I'd rather swim."
    end
end

#============= PRIVATE METHODS =======================
class Test
    def times_two(a)
        puts "#{a} times two is #{engine(a)}"
    end
    def engine(b)
        b*2
    end
    private:engine
end
test=Test.new
# test.engine(6) # fails
test.times_two(6) # 6 times two is 12

#======= MODULES =======================
Math.sqrt(2) # 1.41421
Math::PI # 3.14159
include Math
sqrt(2) # 1.41421
PI # 3.14159
#=======================================

quux = proc {
    puts "QUUXQUUXQUUX!!!"
    }
quux.call # QUUXQUUXQUUX!!!

def run(p)
    puts "About to call a procedure..."
    p.call
    puts "There: finished."
end
run quux

#============= VARIABLES ================
# $ : global variable
# @ : instance variable
# [a-z] or _ : local variable
# [A-Z] : constant
# 2 exceptions: self nil

#====== TRACING OF GLOBAL VARIABLES ===========
trace_var :$x, proc{ puts "$x is now #{$x}" }
$x=5

#======= SPECIAL VARIABLES ===================
$! # latest error message
$@ # location of error
$_ # string last read by gets [NB: LOCAL NOT GLOBAL SCOPE]
$. # line number last read by interpreter
$& # string last matched by regexp
$~ # the last regexp match, as an array of subexpressions [NB: LOCAL NOT GLOBAL SCOPE]
$7 # the eg 7th (or n-th) subexpression in the last match (same as $~[7])
$= # case-insensitivity flag
$/ # input record separator
$\ # output record separator
$0 # the name of the ruby script file
$* # the command line args
$$ # interpreter's process ID
$? # exit status of last executed child process

class Fruit
    attr_accessor :kind, :condition # short for the following:
=begin
    def kind=(k)
    @kind = k    # ie writes
    end
    def kind
    @kind        # ie reads
    end
    ... (similar for condition)
=end
end

f1=Fruit.new
f1.kind="banana"
f1.condition="ripe"
p f1 # same as puts f1.inspect # i.e. for debugging

class Fruit
    def time_passes
        @condition="rotten"
    end
end
f2.time_passes
f2
class Fruit
    def initialize
        @kind="apple"
        @condition="ripe"
    end
end

f3=Fruit.new

class Fruit
    def initialize(k="apple")
        @kind=k
        @condition="ripe"
    end
end
f5=Fruit.new "mango" # a ripe mango
f6=Fruit.new # a ripe apple

=begin
======================================
here are larger blocks of comments
without the need for using # each line
======================================
=end

class Test
    def initialize(k="car")
    @kind=k
    end
end

"Nice day, isn't it?".downcase.split(//).sort.uniq.join



puts '========== END =============='
puts 'Press any key to exit...'
name=gets

Comments