Ruby

From BenningtonWiki

Jump to: navigation, search

Contents

[edit] A Tutorial Introduction

[edit] Getting Started

print("hello, world\n")
$ ruby hello.rb
  • No main()
  • No semicolons
  • Functions, arguments
    • Parens are optional when it's unambiguous; empty argument list is () or no parens at all
  • Escape sequences in strings
print("hello, world
")

[edit] Variables and Arithmetic Expressions

0	-18
20	-7
40	4
60	15
80	26
100	37
120	48
140	60
160	71
180	82
200	93
220	104
240	115
260	126
280	137
300	148
# print Fahrenheit-Celsius table
# for fahr = 0, 20, ..., 300
 
range = 0..300
range.step(20) do |fahr|
	celsius = 5 * (fahr-32) / 9
	printf("%d\t%d\n", fahr, celsius)
end
  • Comments
    • # comment
  • Variable declaration and types
    • Variables do not need to be declared before they're used.
    • Numerics: Fixnum, Float, Bignum
    • Collections: String, Array, Hash, Range
  • Assignment
  • Method calls
range = 0..300
print(range.min)
print(range.max)
  • Iterators, blocks, block parameters
range = 1..10
range.each {print("hello, world\n")}
range = 1..10
range.each do
	print("hello, world\n")
end
range = 1..10
range.each {|x| print(x, "\n")}
range = 1..10
range.each do |x|
	print(x, "\n")
end
  • While loop version
lower = 0
upper = 300
step = 20
 
fahr = lower
while fahr <= upper
	celsius = 5 * (fahr-32) / 9
	printf("%d\t%d\n", fahr, celsius)
	fahr = fahr + step
end

[edit] Loops

Other ways of doing the fahr program.

lower = 0
upper = 300
step = 20
 
fahr = lower
loop do
	break if fahr > upper
	celsius = 5 * (fahr-32) / 9
	printf("%d\t%d\n", fahr, celsius)
	fahr = fahr + step
end
fahr = lower
until fahr > upper
	celsius = 5 * (fahr-32) / 9
	printf("%d\t%d\n", fahr, celsius)
	fahr = fahr + step
end

Scoping: blocks created with do/end or {} introduce new scope, and variables created within the block disappear after the block finishes.

while and until don't create new scope, so variables created within the loop are available afterwards.

In the block versions fahr and celsius are only valid within the loop.

[edit] Symbolic Constants and Globals

LOWER = 0
UPPER = 300
STEP = 20
Lower = 0
Upper = 300
Step = 20
$global_variable = 0

[edit] Object Pool

Bowl of objects. A variable is outside the bowl, and it has yarn tied to it, and the other end of the yarn is tied to its object.

a = "ruby"

Creates "ruby" in the bowl, and ties a piece of yarn from variable a to it.

b = a

Ties a piece of yarn from the same object to variable b.

[edit] Intro

  • Why?
  • What kind of language is Ruby?
  • Uses for Ruby
  • Running Ruby
irb
ruby
#!/usr/bin/ruby

[edit] Some Basic Ruby

"hello world"
5+3
 
def hi
  "hello world"
end
 
hi
hi()
hi(5)
 
def hi(name)
  return "hello " + name
end
 
hi("fred")
  • functions begin with def and end with end
  • no semicolons
  • no need to declare variables or types (result, name, hi)
  • string concatenation with +

Variable names:

  • methods, local variables, parameters: lower case
  • globals: $
  • instance variables: @
  • class variables: @@
  • letters, digits, underscores

[edit] Arrays and Hashes

a = [11, 22, 33, 44, 55]
a[0]
a[1]
a[10]
a[-1]
 
a = ["Jesse", "Aurora", "Max", "Ryan", "Angela", "Mary"]
a[0]
 
a = ["Jesse", 3.14159]
a[1]
a[0].class
 
a[1] = 12345
a[0] = 5678
a[0].class
 
a = []
 
 
h = {"path" => "~/temp", "active" => true}
h["path"]
h["active"]
h["path"] = "~/another"
 
h["fred"]
h[0]
h["fred"] = "was here"
 
h["active"].class
 
h = {}

[edit] Classes

class Pencil
    attr_accessor :number, :length, :brand, :sharpened
end
 
p = Pencil.new
p.number = "2 1/2"
p.length = 7
p.brand = "Ticonderoga"
p.sharpened = true
 
irb> p
=> <Pencil:0x45bb4 @brand="Ticonderoga", @length=7, @number="2 1/2", @sharpened=true>

[edit] Methods

irb> p.public_methods(false).sort
=> ["brand", "brand=", "length", "length=", "number", "number=", "sharpened", "sharpened="]
 
class Pencil
    include Comparable
    def <=>(other)
        return self.length <=> other.length
    end
end
 
q = Pencil.new
q.length = 6
 
a = [p, q]
a.sort!
 
irb> a

Why doesn't 'a' contain 'p' and 'q'? Because 'a' is not tied to the variables, it's tied to the objects that 'p' and 'q' are tied to.

[edit] Control Structures

  • assignments
  • boolean expressions
  • conditionals
  • loops
def hi(number)
    if number > 10
        puts "too high"
    elsif number < 10
        puts "too low"
    else
        puts "just right"
    end
end
 
hi(5)
hi(10)
hi(15)
  • if blocks begin after the conditional, end with end
  • elsif spelling is weird
n = 1
while n <= 10
    puts n
    n += 1
end
 
1.upto(10) do |n|
    puts n
end
 
(1..10).each do |n|
    puts n
end
  • while isn't actually used much
  • oddities: don't use braces for if
  • modifiers: if, unless, while
  • Read to 106

[edit] Ruby is Object-Oriented

  • what: pool, unnamed
  • variables are pointers to the objects
"joe holt".length
-43.abs
 
"joe holt".split
"joe holt".gsub(/o/, "oo")
"joe holt".each_byte {|b| print b, ' '}
 
[1, 3, 6, 2].sort
a = [1, 3, 6, 2]
a.sort
a
a = a.sort
a.sort!
a.each {|x| puts x}
a.pop
a.push(1, 2, 3)
 
class Numeric
  def even?
    (self % 2) == 0
  end
  def odd?
    (self % 2) == 1
  end
end
5.even?
5.odd?
 
5.times {a.pop}
 
1.methods.sort
  • Read chaps 8-11, 23

[edit] Notes and Quotes

Designing Ruby, Doctor Dobb's, January 1, 2001
By Yukihiro Matsumoto

Yukihiro Matsumoto is the creator of Ruby. He can be contacted at matz@zetabits.com.

Designing the ideal language has been a dream of mine since my student days. It wasn't until 1993, however, that I realized that as computers increased in power, new opportunities were opening up for object-oriented programming (OOP) and interpretive (scripting) languages. Over time, I narrowed my interest to Perl and Python, but they still weren't what I wanted. Consequently, I designed Ruby.

When I first read Programming Perl, by Larry Wall, et al. (O'Reilly & Associates, 2000), I was impressed not only by Perl's features and syntax, but by Larry Wall's basic tenants, in particular: "Easy things should be easy, hard things should be possible" and "There's more than one way to do it."

When I started designing what ended up being Ruby, I borrowed the best from languages such C, Perl, Smalltalk, Lisp, CLU, Eiffel, and the like. In the process, I soon realized that computer languages should follow the principles of human-machine interface design, specifically:

  • Consistency. I'm not a minimalist, but I do believe that programming languages should be consistent. A small set of rules should cover the entire language. For instance, in Ruby, all data is an instance of some class without exception. Everything is treated equally.
  • Conciseness. I want my computer to be a servant, not a master, so I'd like to tell it what to do quickly and efficiently. I removed extraneous language elements, such as declarations, static type specifications, and the like. They are all good, but aren't necessary for concise programming. A rich set of literals (as in Perl) helps concise programming, too. In general, Ruby scripts are as concise as Perl scripts, yet far more readable.
  • Flexibility. A language should not restrict expression, but should enhance it. It should be general purpose. "Easy things should be easy, hard things should be possible." But, you know, even hard things can become easy using proper abstraction, thanks to Ruby's deep object-oriented nature.

I also wanted Ruby to be natural to use, and I wanted programmers to feel at ease when coding in it so they can enjoy the act of programming itself. To me, this is the ultimate goal of language design. I have to admit, I don't believe I can satisfy everyone — every programmer has different needs. But I still believe I can satisfy many, including myself.

Programming in Ruby makes me happy, and I've been told that many others like programming in Ruby as much as I do. I want you to enjoy programming and hope Ruby helps you to this end.


Use the Intro comic by why? from Beginning Ruby.


Use the big chart of Cocoa inheritance and as a real-life example. Available in Cocoa Fundamentals, p. 40f.

Personal tools