Last active
November 14, 2016 03:08
-
-
Save r05al/d088dfa574280d551c7c5d48948e9840 to your computer and use it in GitHub Desktop.
Ruby Methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##Method Calls | |
method_name(param1, param2, ...) | |
return_value = method_name param1, param2 | |
mod_return_value = method_name(param1, param2).modify_original_return_val | |
parentheses are optional, unless also passing block | |
Any method can be called with a block as an implicit argument, using yield with a value | |
def followed by method name followed by params enclosed in parentheses, can have default values, or use splat as catch all, | |
can pass hash | |
method body | |
implcitly returns last statement executed | |
can use return to terminate early | |
use break to terminate from block, last value returned from block is returned | |
end | |
ampersand operator as final param indicated method takes a block, takes param to create a Proc | |
Procs | |
blocks of code, bound to a set of local variables as function objects | |
can act as closures | |
def total_after_tax(rate) | |
return Proc.new { |x| x * (1 + rate) } | |
end | |
are first-class objects | |
squared = Proc.new { |x| x*x } | |
def hypotenuse(a,b,squared) | |
c_sq = squared.call(a) + squared.call(b) | |
puts "c^2 is #{c_sq}" | |
end | |
lambda similar to proc, but does argument checking | |
squared = lambda { |x| x*x } | |
Proc.new explicit return returns from enclosing method | |
lambda returns to its caller | |
method is a block of code, always bound to an object and its instance variables | |
global object is Object | |
blocks of code cannot stand alone in code | |
Passing a block to a method, converts the block to a Proc, creates a yield for each element | |
this is implicit | |
Passing a Proc, we must perform #call on each Proc | |
squares = numbers.map {|x| x*x} | |
squared = lambda { |x| x*x} | |
squares = numbers.map {&:squared} | |
when passing a final argument as &some_block, the block is converted to a Proc | |
in the body can be called using some_block.call(param_x) or yield(param_x) | |
can convert Proc into block when using iterators which expect blocks as argument | |
&some_Proc converts to code block and passed to iterator | |
&some_object calls #to_proc on object, implicit conversion, resulting in Proc then converted to block | |
Dynamic methods | |
Singleton method defined on object directly | |
def an_obj.s_method | |
end | |
or | |
an_obj.define_singleton_method(:s_method) { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment