DEV Community

Cover image for An Introduction to Ruby  for Javascript Devs
Christine Garaudy
Christine Garaudy

Posted on • Edited on

An Introduction to Ruby for Javascript Devs

SOME BACKGROUND

Ruby is "a dynamic, open-source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write," according to its docs on ruby-lang.org. Developed in 1995 by Osaka native Yukihiro Matsumoto, who "really wanted a genuine object-oriented with easy-to-use scripting language" as an alternative to Python. Focused on "developer happiness," Ruby is a beginner-friendly language that was intended to be written more closely to human language than its predecessors, using verbs like 'puts' and 'do' for keywords.

Ruby is most commonly implemented with Rails, a framework that extends the language and provides structure and scaffolding to make writing code quicker and easier. It is considered an opinionated framework, as there is typically only one correct way to do a task, making it potentially easier for beginners to learn than a language/framework that has many different ways to achieve the same results. Ruby on Rails works on the backend of an application to fetch from databases and display data that contains HTML, CSS, and JS. With its database-driven design, model-view-controller (MVC) architecture, and built-in testing, Ruby on Rails allows for maximum productivity- one language to rule them all. Many of today's most popular websites were built on the Ruby on Rails framework, including GitHub, Airbnb, Groupon, Hulu, Soundcloud, and Kickstarter.

RUBY VS JAVASCRIPT

Ruby and JavaScript are both object-oriented programming languages that were developed in the same year. Matsumoto designed Ruby with developers' satisfaction in mind, famously stating his intent was to 'help every programmer in the world to be productive, and to enjoy programming, and to be happy.' JavaScript's main goal was to be a programming language that could be run easily and efficiently in web browsers. They are both common first languages for beginners, and both are popular choices for coding bootcamps, but Ruby is often considered easier to learn, mostly because of its brevity, structure, and simpler syntax.

Every programming language must provide ways to iterate over data. Let's check out some simple while loops:

//JavaScript

let x = 1;
while (x <= 10) {
  console.log(`The number is ${x}.`);
  x++;
}

//Ruby 

x = 1
while x <= 10 do 
  puts 'The number is #{x}.'
  x += 1
end

Pretty similar looking, but Ruby's syntax uses verbs that we really use in English, allowing us to tell at a glance what action each line will perform.

A key difference between the two languages is that Ruby is a true class-based language. Although with ES6, JavaScript adopted some keywords like 'class' and 'new' to make it look familiar to programmers coming from other languages, JS is really a classless language. That means that in Ruby, objects are created directly from a class, whereas JavaScript objects are actually created from prototypes.

//JavaScript

class Cat = (name, breed, treats) {
  this.name = name;
  this.breed = breed;
  this.treats = treats;
  this.receiveSnacks = () => {
    treats++;
    console.log(`Enjoy your ${treats} snacks, ${name}, 
you chubby ${breed}!`);
  }
}

garfield = new Cat('Garfield', 'orange tabby', 3);
garfield.receiveSnacks();

//a prototype done with an object constructor


//Ruby

class Cat 
  def initialize(name, breed, treats)
    @name = name
    @breed = breed
    @treats = treats
  end

  def receive_snacks
    @treats+= 1
    puts 'Enjoy your #{@treats} snacks, #{@name}, 
you chubby #{@breed}!'
  end
end 

garfield = Cat.new('Garfield', 'orange tabby', 3)
garfield.receive_snacks 

//a class made with class keyword and initialize method

The class keyword in JavaScript is simply syntactic sugar designed to obscure away some of the complexity of its inheritance methods.

Overall, the languages are overwhelmingly more similar than they are different, and if you have a solid understanding of JavaScript, you should have few problems adapting to Ruby's ways. You may even find that its simplicity saves you a little time.

CONCLUSION

There's a lot of talk online in developer forums about whether Ruby's heyday is over, but the truth is that it doesn't appear to be going anywhere. It did enjoy a resurgence in popularity in the early 20-teens which has since waned a bit, but the language was recently given some tweaks that increased its already-great performance significantly, with a major update just released in May of this year. The language continues to evolve in response to trends and feedback, remaining a solid choice for developers who want to write concise and clean code that is readable and powerful.

Top comments (11)

Collapse
 
michi profile image
Michael Z

There's a lot of talk online in developer forums about whether Ruby's heyday is over, but the truth is that it doesn't appear to be going anywhere.

It appears to be really popular at least over here in Japan. Not sure about other regions.

Collapse
 
ben profile image
Ben Halpern

Nice post, it really helps to get these kinds of 1:1 comparisons.

Collapse
 
wulymammoth profile image
David • Edited

Neat post, Christine! I love that you compared the syntax between JS and Ruby. What caught my eye was my that the first programming language that I spent significant time in was JS even though I had written some Basic, PHP, and Python before it.

A few things...

Ruby is most commonly implemented with Rails

Sorry, I'm a bit of a pendant, but the relationship is inverse -- Rails is, more specifically, a web framework implemented with Ruby. To this day, though, I've always felt "Ruby on Rails" was such a cleverly chosen name that it still rolls off the tongue to this day...

Funnily enough, for as long as I've worked in Ruby, I never knew or ever paid attention to to year/time of Ruby's inception. I only knew about Matz and his motivations.

It is considered an opinionated language, as there is typically only one correct way to do a task

Might be a slight misinterpretation of "opinionated" -- there's a difference between the developer and their opinions when developing code/library/framework for use by other consumers, but there's also the opinion and interpretation of the consuming developers, like you and I that use it. I'm not sure that I've ever heard people say that Ruby is opinionated, but Rails, the framework most certainly is -- both a blessing and a curse as I've worked on small and currently work on a very very large Rails monolith.

I'll speak more to the users of the Rails framework, like you or I. Typically people, including myself, coming from JS will find Ruby's standard library "bloated". There are a multitude of ways to do things in Ruby, one simple example is: obtain the first element in an array:

a = [1,2,3]
first = a[0]
first = a.first
first, second, third = [1, 2, 3] # JS didn't have destructuring until ES6

How about determining if something is zero?

num = 0
num == 0 # true
num.zero? # true (definitely object-oriented)

Glad that you pointed out that JS is a prototypal language compared to Ruby -- the class construct is literally syntactic only to make it more "welcoming" for OO devs

The last thing that I'll point out is that this post seems more of a comparison between JS and Ruby as languages rather than an intro to the Rails framework for JS devs without a JS analog (e.g., SailsJS, HapiJS, etc)

Collapse
 
christinegaraudy profile image
Christine Garaudy • Edited

Thanks for your insights and perspective! I'm new to programming and have more experience with JS than Ruby, but I did experiment with it a bit back around 2015 when it was really hot. I'm curious how long you've been working with Ruby. As a new dev, I appreciate a framework that plays by tighter rules since I'm more apt to making mistakes, but I can understand that someone with more experience might find it limiting. Also, I have heard that many applications, especially those that must manage a lot of requests, would get bogged down with RoR, so Node.js is usually the speedier choice. In your opinion, what kind of applications are better suited to Ruby on Rails?

Collapse
 
wulymammoth profile image
David • Edited

We all start somewhere and welcome aboard! :)

Yeah, Ruby and Rails has certainly lost some of its luster, but continues to make noise -- most recently, DHH (David Heinemeier Hansson), the creator of Rails and his company that's behind Basecamp spent two years on a brand new email service called Hey (hey.com). It is built entirely on with Rails and web-sockets via TurboLinks. It's not "cool" to start new projects today with Rails -- I wouldn't and I haven't, but I'll explain.

I have heard that many applications, especially those that must manage a lot of requests, would get bogged down with RoR, so JS is usually the speedier choice. In your opinion, what kind of applications are better suited to Ruby on Rails?

Rails comes packed with a lot of overhead -- an ORM (ActiveRecord) and SSR (server-side rendering), so it's unfair to compare Rails against JavaScript or NodeJS, the runtime built atop the V8 engine. However, there are benchmarks and both are plenty fast for most use-cases. When people say that languages are "slow", what they really mean are the runtimes are. To understand what I mean, let me digress a bit... a bit of computer science, if you will...

One must familiarize themselves with "Moore's Law" which generally stated that we got 2X speedup about every two years -- this was during the 90s and early 2000s when they kept packing transistors into CPU dies, so without any change to existing code, programs/applications would just run faster, so developers stopped or never needed to think about parallelism or too many optimizations from a software/code perspective, and these were the eras that saw the likes of "single-threaded" languages on their platforms (virtual machines) rise -- Ruby, Python, JavaScript. But as we've discovered in the last decade, hardware has limitations, there is only so small and so many transistors that can be packed into a CPU die before bad things happen, thus we've found ourselves now with multi-core computing systems. Because we can't double speeds anymore, to eek out performance, the onus is now on software developers and people that write code to do so -- we must optimize the instructions sent to the CPU or CPUs.

Parallelism generally means (multiple and disparate pieces of physical hardware, like CPU cores) -- can execute two things at EXACTLY the same time, like washing a pile of dishes that doesn't fit in a single washer, but having the availability of TWO physical washers at your disposal. Concurrency is a similar idea, but we don't have two washers available -- we have one. The difference is imagine that this single washer washes dishes faster than you can load them, therefore, there are moments that the wash is idly waiting for you to reload it. Now, if that washer can perform other functions during that time, you'd likely let it do so -- that's what concurrency is in relation to a CPU. Concurrent programming is writing software that manages to reduce idle resources, like an idle CPU or memory. In most languages, the default programming model is to write code procedurally -- where we are certain that line two runs after line one. If line one takes a long time to do whatever work it needs to do, it "blocks", for example, it may make an external request to some external API from your machine, but the CPU can do something else, it's like a millennia to a CPU while we await that 50ms HTTP response from the external API. JavaScript wraps an asynchronous programming model around this such that it allows us to have code doing other things as it awaits for that request's response. There are languages and runtimes that give us ways to easily control threads of execution and provide us with concepts/constructs to better write parallel and concurrent code. Ruby, by default on our machines run on MRI (Matz Ruby Interpreter), but the same Ruby code put on a different Ruby virtual machine, like JRuby (Ruby on the Java Virtual Machine) with minor tweaks will completely destroy JS running on Node in throughput.

One of the core contributors of Rails, José Valim, left the Ruby and the Rails community when he sought to bring Rails into a more concurrent-friendly future. He ended up creating a new language some of us know today as Elixir that runs atop the Erlang Virtual Machine. Each virtual machine has many language derivatives (e.g. Java Virtual Machine aka JVM has Java, Kotlin, Scala, Clojure, and many more). Elixir has its own super popular framework, called Phoenix which I've worked in and currently use for a side project. It has a Ruby-like syntax with many neat features borrowed from some of the most popular programming languages, but is HIGHLY concurrent and easy to debug. Writing concurrent code in JavaScript, Ruby, or Python is doable and has always been, but there are many pitfalls that make it a challenge. In JavaScript land, a lot of the top libraries, like ExpressJS was built by a guy by the name of TJ Holowaychuk who also left the Node community in search of better ways to do what he needed -- concurrent programming. Instead of Elixir or one of the popular JVM languages like Clojure or Scala, he decided to roll with Go likely due to popularity and its C-like syntax which he has experience in. JavaScript, too, has a C-style syntax.

So that was a long-winded way to answer your question, but to get directly at: "what kind of applications are better suited to Ruby on Rails?" Probably apps where request/response latency is okay -- because NodeJS and its plethora of libraries surrounding the ability to provide more real-time and low-latency support for real-time features over web sockets has more developers doing it. For people that get into web programming and full-stack web development, I'd argue that Rails conventions are a GREAT starting point to go from. It's conventions, while at times restrictive, does provide a level foundation -- those starting out have little idea what to do and why people do things in a particular way and often just run off with a popular tutorial or blog post and think it's "good enough" while possibly learning a bad practice. At least Rails conventions have been vetted by one of the largest community of developers that have managed to "argue" with each other before ultimately deciding on a given convention.

Thread Thread
 
christinegaraudy profile image
Christine Garaudy

I really appreciate this incredibly interesting and super thorough reply! I am definitely looking forward to exploring new languages once I get more programming fundamentals down. Thanks so much for taking the time to read and reply and for giving me ideas for new things to learn about.

Thread Thread
 
wulymammoth profile image
David

You're welcome! Enjoy the journey -- it's never ending and keep writing. I find it a good way to collect and solidify thoughts :)

Collapse
 
shipitko_0 profile image
Anatoly

Good stuff!
What about moving opposite directions from RoR to JS, are there some frameworks like Rails in JavaScript (as for 2020)?

Collapse
 
michi profile image
Michael Z

Yes, Adonis.js is your closest bet.

Collapse
 
christinegaraudy profile image
Christine Garaudy

I'm learning a little about Express.js right now, and I've also heard of Sails.js, which is designed to directly emulate Rails.

Collapse
 
christinegaraudy profile image
Christine Garaudy

Cool, thanks for the info! It's definitely helpful to see how pros are really writing their code.