Understand Javascript callbacks from ruby block

Reading time ~1 minute

Chunk of code

If you are the n00b like me, it should be a hard time to understand the callbacks in JavaScript or block in Ruby. But the two of them, in some way, might share some idea to deal with the problems.

Callback

For example, if you have some ‘chunk of code’ that you want to executes later. How would you do?

In the JavaScript, you put it into function foo (){...} and if you want to execute it. You just pass it into the function as an argument. That’s it.

var names = ['pokemon', 'kitty', 'snoopy' ]
names.forEach(function(name){
  console.log(name);
});

// pokemon
// kitty
// snoopy

In the MDN about forEach(), it describes the callback like this:

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

It executes for each element

why can Javascript do this?

  • Functions are first-class values in JavaScript. You can pass it into another function as arguments.

Easy. A piece of cake. I can pass the functions as argument.

Block in Ruby

Good in JavaScript, right? You pass the chunk of code directly to other function to execute. Can I do the same thing in Ruby?

  • Yes and NO. Yes. There is some different thinking process to deal with it in Ruby. No. You cannot pass directly to the Ruby methods. You can use Proc objects.
 
['pokemon', 'kitty', 'snoopy' ].each do |name|
  puts name
end

It is a similar way to deal with the problem. I have a chunk of code to puts/console.log the name out to the screen. But I may use it later to different arrays. This is the ruby way to solve this problem.

We take a look at the ruby-doc about each:

Calls the given block once for each element in self, passing that element as a parameter. Returns the array itself.

It is some similar between this two.

Higher abstraction

The two languages provide us to think in more abstraction way to solve the problem. They provide us ‘iterate through an array’ and do something else we want it to do. We don’t have to write/define by ourselves each time if we want to iterate through an array to do something. We can directly work on doing something else.

to_param in Ruby on Rails

If I want a custom slug=======================I walk through this cutstom slug.1. create migration `add_slug` to add a column inside the...… Continue reading

What is ORM in Rails mean?

Published on July 14, 2017