DEV Community

Discussion on: Learn Ruby on Rails Best Practices With One Exercise

Collapse
thdaraujo profile image
Thiago Araujo Author • Edited on

Hi, Imanuel!

For sure, Ruby's syntax is a little different. But after you get used to it, writing Ruby code will give you a lot of joy.

You find Ruby a little harder to understand probably because you're used to JS/Go/Java, as they are very similar in style (C-style).

The big difference between Ruby and these other languages is that Ruby is all about objects sending messages to other objects. It's a slightly different way of thinking.

In case you're curious, Ruby is closer to languages like Smalltalk and Lisp. It's a very flexible language based on a small number of basic building blocks.

That flexibility allows you to make your code very readable and descriptive, it's almost like writing english text.

To learn the syntax and the style of a new language, one thing that helps a lot is to look at the basic building blocks of one language and compare it to another.

Then you can try to translate a small piece of code from one language that you understand well to another you're trying to learn.

That's how you spot the differences and similarities, and understand how to apply these ideas in different scenarios.

Let me give you an example.

How would you write a piece of code that prints numbers from 1 up to 10 in Go and Ruby?

Maybe something like this:

# Go
for i := 1; i <= 10; i++ {
  fmt.Println(i)
}

# Ruby
(1..10).each do |n| 
  puts n
end
Enter fullscreen mode Exit fullscreen mode

You can probably see big differences in style. Some basic building blocks we can spot are:

  • a range 1..10
  • the usage of an each iterator instead of a for-loop
  • a block do ... end with a parameter n
  • a puts n method being called with one argument, and no parenthesis

If you compare the two implementations, you might ask these questions:

  • Ruby has for loops, but why are we iterating over a range here?
  • Is each a method call on range?
  • Why are we using do |n| ... end instead of { |n| ... }?
  • What if you change the code to puts(n)?

Or even a slightly harder question:

  • Would you be able to send a message to a variable or object in Go? Why not? Example:
# sending a message instead of calling a method
 (1..10).send(:each) { |n| puts n }
Enter fullscreen mode Exit fullscreen mode

You can learn a lot about Ruby just by trying to answer one of these questions. And then trying to write a similar piece of code by yourself and practice what you've just learned.

You'll learn not only the style and syntax of Ruby, but also the mindset behind it. This exercise is useful for learning any other language, just change the questions a bit and practice.

Hope that helps!

Collapse
nathanael_79 profile image
Imanuel Ronaldo

Hi Thiago, thanks for the advice, it helped me a lot, time to Learn Ruby more! thanks!