Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to indent my code in Ruby?

Tags:

ruby

You would think that this would be an easy question, but I can't find the answer anywhere. >_<

Will Ruby throw syntax errors if my code is indented incorrectly? For example, would code like this work?

if str.blank?
  str = "Hello World"
no_input = true
  end

Obviously, this is bad style and I should indent correctly regardless. I want to know whether I can rule it out as the cause of a bug during debugging sessions.

like image 610
Kevin Avatar asked Jun 11 '13 19:06

Kevin


2 Answers

Yes, it would work. Ruby only looks for the line breaks.

But since code readability is also very important, I'd say you should take care of whitespace if only for that sake.

like image 96
Marcelo De Polli Avatar answered Oct 23 '22 19:10

Marcelo De Polli


Indentation is (Usually) a Stylistic Choice

In Ruby, indentation per se is not relevant, although the location of linebreaks and other whitespace may cause ambiguity for the parser or cause it to consider certain things as separate expressions when you didn't mean for them to be. Here-documents and multi-line strings are also areas where indentation will matter.

In all cases, the real question is "what does the parser see?" In your example, it should be functionally equivalent to the properly-indented code. However, if you really want to know what's going on under the hood, take a look at Ruby's Ripper module to see how your code is actually being parsed.

like image 22
Todd A. Jacobs Avatar answered Oct 23 '22 21:10

Todd A. Jacobs