Tutorial by Examples

def call_the_block(&calling); calling.call; end its_a = proc do |*args| puts "It's a..." unless args.empty? "beautiful day" end puts its_a #=> "beautiful day" puts its_a.call #=> "beautiful day" puts its_a[1, 2] #=> "It'...
# lambda using the arrow syntax hello_world = -> { 'Hello World!' } hello_world[] # 'Hello World!' # lambda using the arrow syntax accepting 1 argument hello_world = ->(name) { "Hello #{name}!" } hello_world['Sven'] # "Hello Sven!" the_thing = lambda do |magic, ...
Putting a & (ampersand) in front of an argument will pass it as the method's block. Objects will be converted to a Proc using the to_proc method. class Greeter def to_proc Proc.new do |item| puts "Hello, #{item}" end end end greet = Greeter.new %w(world l...
Blocks are chunks of code enclosed between braces {} (usually for single-line blocks) or do..end (used for multi-line blocks). 5.times { puts "Hello world" } # recommended style for single line blocks 5.times do print "Hello " puts "world" end # recomme...
Objects that respond to to_proc can be converted to procs with the & operator (which will also allow them to be passed as blocks). The class Symbol defines #to_proc so it tries to call the corresponding method on the object it receives as parameter. p [ 'rabbit', 'grass' ].map( &:upcase ) ...
Technically, Ruby doesn't have functions, but methods. However, a Ruby method behaves almost identically to functions in other language: def double(n) n * 2 end This normal method/function takes a parameter n, doubles it and returns the value. Now let's define a higher order function (or met...

Page 1 of 1