26
loading...
This website collects cookies to deliver better user experience
{..}
or the do..end
syntax.{..}
is used for single line blocks, while do..end
syntax is used to encapsulate multiple lines of code.return
keyword inside a block unless you have a really good reason for it. Lets explore why..return
keyword always belong to methods, so in the second example when words.map
iterates over the array, it instantly returns the first word it encounters and yell_words
ends immediately with the output of "LION!" which is not at all what we were expecting. This is a common pitfall for programming newbies, and I surely have been a victim numerous times.Array.select
and passing in the argument &:odd?
. The :odd?
part is just a symbol that refers to the Integer#odd?
'method', which will be called on every element of the array, and &
is used to convert the 'method' into a Proc(a normal Ruby object) that can be passed into select
.&
from the block's example, earlier? Lets see how it works:&prc
as the third argument of the method, combine_and_proc
must always be called with a block or it will throw an error. The block will be taken by the &prc
argument, and &
will turn the block into a proc. Now when we call puts prc.call(word)
inside combine_and_proc
there will be no errors because prc
was turned into a proc by Ruby automatically.&
can do for us, and that is to turn a proc into a block. Yes, it might sound confusing but it works both ways. Lets take a look:select
takes in a block as its last argument. Then, we created the proc odds
and passed it like this [1,2,3].select(odds)
and so we get an error because odds
is a proc and select
is expecting a block. So the correct way would be to call select with &odds)
because &
will turn the proc into a block right before giving it to the select
method.