Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby code blocks versus javascript anonymous functions distiction

I’m doing my first internship and it's going good and I'm trying to keep up with everything the other programmers talk about. A senior programmer told me the other day that Ruby’s ability to pass code blocks directly into functions was much more preferable than using anonymous functions in JavaScript. It’s my understanding that JS anonymous functions are precisely the same thing – simply passing a code block via a variable as a parameter. Are there real-world examples of code block parameters being superior to anonymous functions? Or is it simply a matter of preference in one language over the other, a code readability/re-usability issue, or am I simply misunderstanding some other fundamental concept? This was a passing conversation about the relative merits of which language to use for some task, and not a concrete work problem, which is maybe why I’m confused. I Googled a couple naive examples of code blocks and had little trouble implementing them in JS. Looking forward to any input on the matter (anonymous or otherwise).

like image 355
ialexander Avatar asked Dec 22 '13 19:12

ialexander


People also ask

What is the difference between a block and method Ruby?

A block is the same thing as a method, but it does not belong to an object. Blocks are called closures in other programming languages. There are some important points about Blocks in Ruby: Block can accept arguments and returns a value.

What is the difference between block and function?

Unlike functions, they can't stand alone. A block is a chunk of code that can be invoked kind of like a function, but not quite like one: a block only appears adjacent to a function call such as . each , and that function may or may not use that block by “invoking” it (executing the code inside it).

What is the difference between procs and blocks?

Ruby introduces procs so that we can pass blocks. Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code can be called in different contexts and still access those variables.

What is a Ruby code block?

A ruby block is one or more lines of code that you put inside the do and end keywords (or { and } for inline blocks). It allows you to group code into a standalone unit that you can use as a method argument.


1 Answers

They are not exactly the same. The main reason is the use of implicit and explicit return values.

You can read a good article here: http://yehudakatz.com/2012/01/10/javascript-needs-blocks/

like image 153
phoet Avatar answered Sep 18 '22 20:09

phoet