Tips for switching between Ruby & JavaScript

Muesingb
2 min readDec 5, 2019

--

Trying to clear out the cobwebs of your brain to remember simple differences between Ruby and Javascript? Here are some simple things to not get tripped up over.

confused math lady meme — math is hard
After this post, you won’t feel like this anymore

Some Major Conceptual Stuff

  • Ruby uses practical object-oriented programming (P.O.O.P.), while JavaScript is mainly functional with some object-oriented capabilities
  • Many of the enumerables in ruby that apply to all objects are not available in Javascript

Examples

Hi, how are ya, default? Shoveling is crazy, right?
You can interpolate with quotations Hi, how are ya, default? Shoveling is crazy, right?
1
2
3
1
2
3
Terminal prints: Hi, how are ya, default?
Need to interpolate with backticks Hi, how are ya, default?
1
2
3
1
2
3

Here’s a breakdown of what we’re seeing in these examples:

  1. Commenting

Ruby: ##

JS: //

2. Variable Declaration

Ruby: Nothing special needed, just use = to set the value

JS: Use keywords let or const. let allows value to change, const does not

3. Naming Conventions (in general, see documentation for more specific examples)

Ruby: snake_case

JS: camelCase

4. Declaring Functions/Methods

Ruby: def method_name(parameters) end. Doesn’t need parentheses if there are no parameters

JS: function functionName(parameters) { }. Needs parentheses even if there are no parameters. Doesn’t need to use end.

5. Conditional Statements

Ruby: if condition elsif end

JS: if (condition) { } else if { }

6. Interpolation

Ruby: #{ }

JS: `${ }` Make sure it has back-ticks

7. Shoveling

Ruby: << An alternative to .push( ) and only Ruby has it

8. Printing to the Console

Ruby: puts, prints, p

JS: console.log( )

9. Returning from functions/methods

Ruby: Returns implicitly

JS: Need to return explicitly using return keyword!!

10. Calling functions/methods

Ruby: Just write method name to call it

JS: Need to add ( ) in order to call function. Without it, it will just reference it. functionName( )

11. Iterating over arrays

Ruby: array.method {|arrayIndex| work}. Also works with hashes.

JS: Uses a callback function: array.method(function(arrayIndex) {work}). Cannot iterate through objects that are not arrays using these methods. Need to use a for…in loop.

12. {key: value}

Ruby: Hashes

JS: Objects

Note that objects in Javascript and hashes in Ruby are not perfectly comparable, but they do each hold key/value pairs.

--

--