class You
def ask_questions
…
end
end
class Me
def keep_on_track
…
end
end
Time.now + 30 * 60
“Modern” Ruby.
Slide Time: 00:02 (00:04)
First released in 1995 by Japanese Programmer “Matz”.
Syntax influenced by Perl (C-style).
Features influenced by Smalltalk and Lisp.
Modern Ruby began with v1.9 (2007)
Several Implementations, main is MRI.
ruby.is_a?(Language) &&
ruby.typing?(:dynamic) &&
ruby.memory?(:gc) # => true
class Person
def initialize (first, last)
@first_name = first
@last_name = last
end
def name
@first_name + " " + @last_name
end
end
character = Person.new("Sheldon", "Cooper")
character.name
begin...end
or do...end
.void
functions).Consider this irb
session:
>> 1.class
=> Fixnum
>> "Hello World".class
=> String
Open irb
and experiment with the following:
true
and false
(0..10).class
Slide Time: 00:06 (00:25)
def create_logger
logger = if $stdout.tty?
Logger.new($stdout)
else
Logger.new("events.log")
end
…
end
if
statement is really an expression.if
in string interpolation.Open irb
and let’s play with some expressions together.
if true then "hello" end
if false then "hello" end
class Customer < Person
include(UniqueID)
private(:make_unique_id)
end
module UniqueID
def make_unique_id
…
end
end
Consider this irb
session:
>> String.class
=> Class
>> anon = Class.new do
?> def hello; "hi"; end
>> end
>> object = anon.new
>> object.hello
=> "hi"
list = ["Jasmine", "Lavender", "Lilac"]
# Long-form block.
list.each do |item|
$stdout.puts("I like #{item}!")
end
Array#each
).Open irb
and play with long- and short-form blocks.
list = ["Jasmine", "Lavender", "Lilac"]
# Long-form block.
list.each do |item|
$stdout.puts("I like #{item}!")
end
# Short-form block.
list.each {|item| puts(item)}
do |x| ... end
.{|x| ... }
.# Exception-safe file closing.
File.open("/dev/urandom") do |file|
bytes = file.read(10)
…
end
# Exception-safe database transactions.
transaction do
record_a.save!
record_b.save!
end
File::open
).Open irb
and ask some questions!