Skip to content

Instantly share code, notes, and snippets.

@jessemcready
Created September 23, 2018 17:41
Show Gist options
  • Save jessemcready/1b7784a2e3aea945eca0685290155812 to your computer and use it in GitHub Desktop.
Save jessemcready/1b7784a2e3aea945eca0685290155812 to your computer and use it in GitHub Desktop.

From Ruby To Javascript

When I'm learning new things, I find it easier to find an equivalent to something that I already know and tweak it to fit the new thing I'm learning. It's no different in learning a new programming language, because most languages have the same core ideas but the syntax is different. I'm going to discuss the two topics that gave me the most trouble and the Ruby alternative that finally made these ideas click. Just a warning, these relationships are not exact, it's just a way to help me(and hopefully you) to have an easier time learning.


Classes

https://gist.github.com/09b91036f8c62097d24f85adab1ee216

https://gist.github.com/80cc86e18d9cadb2175c915c44be09ae

These two code blocks describe the same thing. This creates a Person class that has an attribute of name. Notice that with Ruby, we need to have an attr_accessor that will create a getter and setter method for that particular attribute. JavaScript however, does not need to write getter and setter methods, you are able to just access the classes attributes using dot notation.

The syntax for calling these classes is also slightly different but perform the same task. Both languages use new but in different places. In both cases, the new keyword points to a default function with a specific name. In JavaScript, you look for constructor() and in Ruby you look for initialize.


Callbacks

At first, callbacks were one of the most difficult ideas to get down. Having a funciton take in a function as a parameter was hard to wrap my head around. I got the idea to stick by looking back to Ruby. https://gist.github.com/2b2fffd8f9ccbe6f34b655d3772b0763

https://gist.github.com/997902d45429c3fd959a1c2fb681af0a

The way I started to think about it was that callback functions are just blocks of code we pass to functions. We have blocks in Ruby, and they go between do and end keywords. The similarity is easier to see when you write the above code as one-liners. https://gist.github.com/47f0eee87acde45f12cf85b5d1c825d3

https://gist.github.com/08d4bd381e40c6f0a0183a3f9c23f56a


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment