Ruby for newbies Lake Ainsworth

Embed Size (px)

Citation preview

Ruby for Newbies

Andrew GrimmUniversity of NewSouth Wales

What is Ruby?

Multi-paradigm languageObject-oriented programming

Functional programming

Procedural programming

Just about everything is an Object

>> 42.is_a?(Object)

=> true

>> "hello world".is_a?(Object)

=> true

>> nil.is_a?(Object)

=> true

>> Object.is_a?(Object)

=> true

>> Class.is_a?(Object)

=> true

Just about all instructions are methods

puts hello world is a call to the method `puts`

>> private_methods.grep(/puts/)

=> ["puts"]

Enumerations

(1..5).each {|x| puts x}

(1..5).map {|x| x * 2}

(1..5).find_all {|x| x.odd?}

(1..5).sort_by {|x| [x.odd?.to_s, x]}

(1..5).group_by {|x| x.odd?}

Ruby (kind of) does functional programming

grouping_by = Proc.new {|x| x % 6 }

what_to_do = Proc.new {|x| p x}

numbers = 1..50

def group_by_and_process(numbers, grouping_by, what_to_do)

what_to_do.call(numbers.group_by(&grouping_by))

end

Metaprogramming

plus = :+

number_1 = 12

number_2 = 30

number_1.send(plus, number_2) # => 42

You can do just about anything

old_stdout = STDOUT

STDOUT = StringIO.new

STDOUT.puts "this won't be printed"

STDOUT = old_stdout

STDOUT.puts "this will be printed"