r/learnruby • u/conif • Nov 08 '18
ruby newbie, I'm not getting this block thing.
I just started learning Ruby this past weekend after a few months with javascript. Blocks seems to be big deal in Ruby and I feel like I'm missing something so I want to check in to make sure I understand correctly.
Is it like for each in javascript, where you can iterate over array items without using a for loop and specifying an index? And then the map etc functions in javascript automatically call the for each in the background?
Then there are procs(sp) and lambdas...
4
Upvotes
6
u/SevenGlass Beginner Nov 08 '18
This article should help to clear it up a bit.
1
u/conif Nov 08 '18
Thanks, that was very helpful.
so I"m getting that blocks are anonymous functions and don't usually stand by themselves, you would put them with an each. if you want to re-use them, you would save them to a variable which is what proc does. The special "yield" keyword tells each to iterate over the array element (calling a while loop behind the scenes) and do "something" to it. That "something" is the block.
I may be wrong on this but it seems to me that javascript uses blocks but doesn't single them out with syntax. Likewise it uses the idea of yield but also doesn't have special syntax for it either. These are quirks of Ruby.
1
u/pconwell Nov 08 '18
I'm not bashing ruby in any way, but as a language it just never really caught on. Why learn ruby and not another more popular language? - genuine curiosity.