comparison 1-Ruby/code-blocks.rb @ 17:61dfac9a058a

Add some initial experiments with blocks
author IBBoard <dev@ibboard.co.uk>
date Tue, 03 Jan 2017 20:58:19 +0000
parents
children e58952c15e5e
comparison
equal deleted inserted replaced
16:8d46064c9afc 17:61dfac9a058a
1 #! /usr/bin/env ruby
2
3 # Simple passing of code block
4 3.times { puts 'Repeated string' }
5
6 # Extending a class
7 class Fixnum
8 def my_times
9 # We're in a number, so store it as an iterator
10 i = self
11 until i == 0
12 i = i - 1
13 # Magic happens here!
14 # Yield normally yields a value, but somehow we're executing a blockā€¦
15 yield
16 end
17 end
18 end
19
20 3.my_times { puts 'My repeated string' }
21
22 # Blocks are objects, if you do it right - https://www.ruby-forum.com/topic/49018
23 my_block = proc { puts 'I am a block' }
24 puts my_block.class
25
26 # Blocks can be passed around - "&var" says "this is a block"
27 def call_block(&block)
28 block.call
29 end
30 def pass_block(&block)
31 call_block(&block)
32 end
33 pass_block { puts 'Inline block' }
34 pass_block &my_block
35
36 # Without the "&" we get "wrong number of arguments (1 for 0)" because
37 # a block and an argument are different somehow. This is *not*
38 # because we were trying to call "my_block" and pass what it returned (nil).
39 # I tried. Calling a block definitely needs ".call"
40 #
41 # This page (https://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes)
42 # makes it cleared: ANY method can take a block independent of its arguments.
43 # That means that this works:
44 def pass_var_block(block)
45 call_block(&block)
46 end
47
48 pass_var_block my_block