Travails of a RubyJavascript Dev (1)

Kayode Adeniyi
2 min readMar 13, 2017

--

I started out as a Ruby developer then eventually took on Javascript. I’ve spent over 3 years dabbling in Ruby and over 2 years in Javascript. I see Ruby as my first love due to the fact that it’s syntax is quite simple and easy to read. My assumption has always been that almost all the inbuilt methods that have the same name will work almost the same way in both Ruby and Javascript.

Recently, I decided to do a couple of operations which I expect to give me the same result in both Ruby and Javascript: Array#sortand Array#reverse . So I worked with three arrays a = [5, 3, 9, 2, 1], b = [10, 1, 2, 5] and c = ['a', 'c', 'b', 'y', 'u'] .

In ruby

a.sort
=> [1, 2, 3, 5, 9]
a.reverse
=> [1, 2, 9, 3, 5]
b.sort
=> [1, 2, 5, 10]
b.reverse
=> [5, 2, 1, 10]
c.sort
=> ["a", "b", "c", "u", "y"]
c.reverse
=> ["u", "y", "b", "c", "a"]

In Javascript

console.log(a.sort())
=> [1, 2, 3, 5, 9]
console.log(a.reverse())
=> [1, 2, 9, 3, 5]
console.log(b.sort())
=> [1, 10, 2, 5]
console.log(b.reverse())
=> [5, 2, 1, 10]
console.log(c.sort())
=> ['a', 'b', 'c', 'u', 'y']
console.log(c.reverse())
=> [ 'u', 'y', 'b', 'c', 'a' ]

Observations

Array#sort

  • While sorting in Ruby gives the result in ascending order of numbers on the number line, Javascript gives it in the ascending order of numbers on the ASCII table.
  • Sort is destructive (changes the original array) in Javascript but not in Ruby. This destructive nature is enough to cause a bug in your program if not known
  • They both give the same result for alphabets.

Array#reverse

  • They both return the same value.
  • Reverse is destructive (changes the original array) in Javascript but not in Ruby. This destructive nature is enough to cause a bug in your program if not known

Conclusion

  • As much as you might want to rely on built-in methods, always try to checkout whether they give the expected result by checking with an input that you already know what the output should be.
  • When sorting numbers in Javascript, always consider passing a compare function into it so that you can be sure of what the result will be. Passing a simple function function(a, b){return a — b} into sort is okay for number sorting.
console.log(b.sort(function(a, b){return a — b}))
=> [1, 2, 5, 10]
  • Sort and Reverse in Javascript are destructive by default while that of Ruby is not. If you need to perform a destructive sort in Ruby then the methods should be called with a ! . For example
a.sort!
=> [1, 2, 3, 5, 9]
a
=> [1, 2, 3, 5, 9]

I hope this fixes a bug in someone’s code.

#7

--

--