learning ruby - 7

5
Learning Ruby - 7 Methods

Upload: nomlanga-kirby

Post on 02-Jan-2016

24 views

Category:

Documents


4 download

DESCRIPTION

Methods. Learning Ruby - 7. Ruby Methods are Easy!. def addem ( first, second ) first + second end # of addem. addem( 23, 6 ) def addemall ( first, *rest ) rest.each { |r| first = first + r } first end # of addemall. addemall( 1, 2, 3, 4, 5, 6, 7 ). Yield. def block_sent? ( what ) - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Learning Ruby - 7

Learning Ruby - 7

Methods

Page 2: Learning Ruby - 7

def addem ( first, second )first + second

end # of addem.

addem( 23, 6 )

def addemall ( first, *rest )rest.each { |r| first = first + r }first

end # of addemall.

addemall( 1, 2, 3, 4, 5, 6, 7 )

Ruby Methods are Easy!

Page 3: Learning Ruby - 7

def block_sent? ( what )if block_given?

yield( what )else

whatend # of if.

end # of block_sent?

block_sent?( 22 )

block_sent?( 22 ) { |num| num*num }

block_sent?( 22 ) { |num| num+num }

Yield

Page 4: Learning Ruby - 7

def give_back ( a, *b )return a

end # of give_back.

give_back( 10 )give_back( 10, 11 )

def give_back2 ( a, *b )return a, b.flatten

end # of give_back2.

give_back2( 10 )give_back2( 10, 11 )give_back2( 10, 11, 12, 13 )first, rest = give_back2( 1, 2, 3, 4, 5 )

Fun with return

Page 5: Learning Ruby - 7

More ... Ruby So Far

Methods can take no, a fixed number or a variable number of parameters as arguments

The value of the last statement executed is returned by the method (unless an explicit return is used)

Methods are what you use to build classes in Ruby