Are your Ruby code looking good?

Are your Ruby code looking good?
Average rating: 0
(0 votes)

Thanks! You’ve rated this material!

What is your coding style?

Are you writing good looking ruby?

Are you sure?

Nearly everybody is convinced that every style but their own is ugly and unreadable. Leave out the “but their own” and they’re probably right…
Jeffy Coffin

Pay attention on most popular Ruby Style Guide by Bozhidar Batsov.

It based on feedback and suggestions from members of the Ruby community and various highly regarded Ruby programming resources.

If you are on Rails you might want to check out the Ruby on Rails Style Guide.

But let’s go back to the Ruby Style Guide. You’ll find there best practices for real-world Ruby developers so they can write Ruby code that can be maintained by other real-world Ruby developers. Let’s look at some examples!

Use spaces around operators, and curly braces (‘{‘, ‘}’) after commas and semicolons

sum = 1 + 2
a, b = 1, 2
1 > 2 ? true : false; puts "hi"
.each { |e| puts e }

No spaces after ‘(‘, or between braces (”).


Indent when as deep as case.

when song.name == 'Tik Tok'
  puts "Not again!"
when song.duration > 120
  puts "That's really long"
when Time.now.hour > 21
  puts "It's time to start coding"

epoch = case year
        when 1607..1777 then "Colonial Period"
        when 1778..1812 then "Early Republic"

Use def with parentheses when there are arguments. Omit parentheses when the ruby method does not accept any arguments

def some_method
  # payload

def method_with_arguments(arg1, arg2)
  # payload

Favor the ternary operator over if/then/else/end constructs. It’s more common and concise.

# bad
result = if some_condition then something else something_else end

# good
result = some_condition ? something : something_else

Use one expression per branch in a ternary operator. This also means that ternary operators must not be nested. Prefer if/else constructs in these cases.

# bad
some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else

# good
if some_condition
  nested_condition ? nested_something : nested_something_else

Need automation tool for analyzing/correction your ruby code? Meet RuboCop – Ruby static code analyzer.

Let’s make our world better together! ✍(◔◡◔)

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111