Ruby Language

Fall 2014 (Week 10)

Ruby

  • A scripting/interpreted language.
  • Purely object-oriented.
  • Metaprogramming
    • Program that writes or manipulates other programs.

Execution

  • Interactive Ruby
    • irb
  • Run script
    • ruby [script_file.rb]

Variables

  • No variable declarations.
  • Scope

Local variable

ex) foo

Global variable

ex) $foo

Instance variable in an object

ex) @foo

Data Types

  • Numbers
  • Strings
  • Symbols
  • Arrays
  • Hashes

Symbols (Data Types)

  • Immutable string whose value is itself
  • Notation: :foo

:foo.to_s == "foo"

"foo".to_sym == :foo

:foo == "foo" #=> false

Arrays, Hashes

  • Arrays

x = [1, 'two', :three]

x[1] == 'two'; x.length == 3

  • Hashes

y = {'a' => 1, :b => [2, 3], c: 4}

y[:b][0] == 2; y.keys == ['a', :b, :c]

Methods

  • Definition

def greeting

puts "Hello World!"

end

  • Invocation

> greeting

Hello world!

Methods (2)

  • Definition

def greeting(name)

puts "Hello #{name}!"

end

  • Invocation

> greeting yongchun

Hello yongchun!

Iterators

x = 1

while x < 10 do

puts x

x = x + 1

end

for i in 1..10 do

puts i

end

Iterators (2)

array = [12, 34, 532, 234]

for i in array do

puts i

end

array.each do |val|

puts val

end

Classes

class Person

def initialize (name, age)

@name = name

@age = age

end

def name

@name

end

def name=(value)

@name = value

end

Classes

a = Person.new("yongchun", 25)

a.name = "yongfal"

Classes (2)

class Person

attr_accessor :name

attr_accessor :age

def initialize (name, age)

@name = name

@age = age

end

end

Classes (3)

  • Instance methods of a class.

ex) Person.instance_methods

  • Instance methods not defined by ancestors.

ex) Person.instance_methods(false)

Reference

[Week10]RubyLanguage - Google Slides