Mercurial > repos > other > SevenLanguagesInSevenWeeks
view 1-Ruby/code-blocks.rb @ 101:1fae0cca1ef8
Reduce large maze to single width corridors
This reduces the permutations for
a x
x x
b x
To one (two steps north) from four (two steps north; one east, two north, one west; one east, one north, one west, one north; and one north, one east, one north, one west). Longer corridors were worse!
We would filter this in the "been here before via another path" but that's still a lot of lookups in lists, which is inefficient.
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sun, 14 Jul 2019 13:42:24 +0100 |
parents | e58952c15e5e |
children |
line wrap: on
line source
#! /usr/bin/env ruby # Simple passing of code block 3.times { puts 'Repeated string' } # Extending a class class Fixnum def my_times # We're in a number, so store it as an iterator i = self until i == 0 i = i - 1 # Magic happens here! # Yield normally yields a value, but somehow we're executing a blockā¦ yield end end end 3.my_times { puts 'My repeated string' } # Blocks are objects, if you do it right - https://www.ruby-forum.com/topic/49018 my_block = proc { puts 'I am a block' } puts my_block.class # Blocks can be passed around - "&var" says "this is a block" def call_block(&block) block.call end def pass_block(&block) call_block(&block) end pass_block { puts 'Inline block' } pass_block &my_block # Without the "&" we get "wrong number of arguments (1 for 0)" because # a block and an argument are different somehow. This is *not* # because we were trying to call "my_block" and pass what it returned (nil). # I tried. Calling a block definitely needs ".call" # # This page (https://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes) # makes it clearer: ANY method can take a block independent of its arguments. # # That means that this works, because we're taking an argument then treating it like # a block: def pass_var_block(block) call_block(&block) end pass_var_block my_block