Table of contents
1.
Introduction 
2.
Execution of Ruby Program
3.
Lexical Structure in Ruby
4.
Whitespace
5.
Whitespace in Ruby
6.
Newlines as statement terminators
7.
Spaces and method invocations
8.
Frequently Asked Questions
8.1.
How can we remove Whitespace in ruby?
8.2.
Does Ruby care about Whitespace?
8.3.
What language is sensitive to Whitespace?
8.4.
What does Strip do in Ruby?
8.5.
What is meant by keyword and Whitespace in Ruby?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Whitespace in ruby

Author Apoorv
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Ruby

Ruby is an object-oriented programming language that is general-purpose, dynamic, and reflective. Except for blocks, which have replacements in the form of procs and lambda, everything in Ruby is an object. The goal of Ruby's development was to create a user interface between human programmers and the computational machinery that underpins them.

Ruby's syntax is similar to many other programming languages, including C and Java, making learning easy for Java and C programmers. It runs on various operating systems, including Windows, Mac OS X, and Linux.

Let's talk about Whitespace in ruby and how to do it in Ruby. Before getting deeper into whitespace let's first understand the execution of the ruby program along with the lexical structure then whitespace will be easy to understand.

Execution of Ruby Program

Every time a ruby program is executed, it is first lexed into tokens, followed by the assembly of the tokens into an abstract syntax tree (AST), and ultimately the compilation of the AST into virtual machine instructions.

Every time you run a Ruby program, the language runs through each character in the program one at a time, grouping them into what are known as "tokens" or special words. There is no assurance that these tokens are genuine Ruby. The token stream may be invalid at this point. The parser is in charge of determining whether or not the inputted program is valid.

Lexical Structure in Ruby

Computer languages adhere to a lexical structure, much like human languages do. Tokens make up the source code of a ruby program. The Ruby interpreter parses any program as a series of these tokens when parsing it. Ruby has literals, punctuation, comments, identifiers, and keywords among its token types. You will learn about one form of token in this article: literals in ruby. Additionally, tokens contain crucial details about the characters that make up the tokens and the whitespace that separates them. Now we are clear about how the ruby program is executed and are familiar with lexical structure in ruby now we can move forward to whitspace in ruby.

Whitespace

Whitespace is any character or sequence in computer programming that represents horizontal or vertical space in typography. A whitespace character does not correlate to a visual mark when rendered, but it often takes up space on a page. Now let's see Whitespace in Ruby.

Whitespace in Ruby

Before getting deeper into Whitespace in Ruby, let's first understand a bit about tokens. Spaces, tabs, and newlines are not tokens but are used to separate tokens that would otherwise merge into a single token. Tokens are atomic code elements. 

We have various lexical structures in Ruby language, such as comments, variables, literals, white space, operators, delimiters, and keywords. Aside from this essential token-separating function, most Whitespace is ignored by the Ruby interpreter and is used to format programs to make them easy to read and understand. Not all Whitespace is ignored, however. Some are required, and some whitespace is forbidden. Although rich and expressive, Ruby's syntax has a few instances where adding or removing Whitespace might alter the meaning of a program. Despite the rarity of these situations, it is important to be aware of them.

Newlines as statement terminators

The most common form of whitespace dependency involves newlines as statement terminators. Every statement must be terminated with a semicolon in languages like C and Java. In Ruby, you can also use semicolons to end statements, but doing so is only necessary if you have multiple statements on a single line. Semicolons must be avoided elsewhere by convention.

The Ruby interpreter must determine where statements stop on their own in the absence of explicit semicolons. Ruby utilizes the newline as the statement terminator if the code on a line contains a syntactically complete statement. If the statement is incomplete, then Ruby continues parsing the statement on the next line.

If all of your statements fit on a single line, there won't be a problem. However, if they don't, you need to be careful to break the line so that the Ruby interpreter can't treat the first line as a statement on its own. Your software may respond differently depending on where you place a new line, which is where the whitespace dependency sits.

Example: 

the following code adds x and y and assigns the sum to the total: 

total = x + # Incomplete expression, parsing continues y

 

But this code assigns x to total and then evaluates y, doing nothing with it: 

total = x # This is a complete expression + y # A useless but complete expression.

 

Take the return and break statements as still another illustration. An expression that gives a return value may optionally come after these statements. A new line between the keyword and the expression will terminate the statement before the expression. Invoking a method, using an array literal, or using a hash literal all allow you to introduce a new line without worrying about prematurely ending your statement after an operator or after a period or comma.

You can also escape a line break with a backslash, which prevents Ruby from automatically terminating the statement:

var total = first_long_variable_name + second_long_variable_name \ + third_long_variable_name # Note no statement terminator above.

Spaces and method invocations

The parentheses around method invocations may occasionally be omitted in Ruby's grammar. This is a crucial aspect of Ruby's beauty since it enables methods to be used just like statements. Unfortunately, it creates a dangerous dependency on whitespace. Consider the following two lines, which differ only by a single space:

f(3+2)+1 

f (3+2)+1

The first line adds 1 to the outcome after passing the function f the value 5. Ruby considers that the parentheses surrounding the method call have been dropped because the second line has a space after the function name.cy. The parentheses that appear after the space are used to group a subexpression, but the entire expression (3+2)+1 is used as the method argument. If warnings are enabled (with -w), Ruby issues a warning whenever it sees ambiguous code like this.

The solution to this whitespace dependency is straightforward:

  • A method name and the beginning parenthesis should never be separated by a space.
  • If the first argument to a method begins with an open parenthesis, always use parentheses in the method invocation. For example, write this f((3+2)+1).  
  • Always try to run the Ruby interpreter with the -w option, so it will warn you if you forget either of the rules above!

Check out this article - Balanced Parentheses

Frequently Asked Questions

How can we remove Whitespace in ruby?

We can remove Whitespace in ruby using some inbuilt functions. We can use .strip to remove only leading and trailing Whitespace (similar to PHP's trim), but you can also use .sub(/s+/, "") to remove all Whitespace.

Does Ruby care about Whitespace?

Because Ruby ignores Whitespace (spaces and blank lines), the print statement does not need to be indented. However, Rubyists (Ruby fans) adhere to this convention. Thus it's a good idea to get into the habit immediately. Following an if, the code block should be indented two spaces.

What language is sensitive to Whitespace?

Whitespace enforces the structure of code in Python. Whereas in C, it's only a convention, so you can "lie" with it.

What does Strip do in Ruby?

Strip method is used to remove the leading and trailing Whitespace on strings, including tabs and newlines. 

What is meant by keyword and Whitespace in Ruby?

To separate tokens and end statements in the source file, Ruby uses white space. It's also used to make the source code more readable. If true, the string "A message" is terminated. In some cases, white space is required. Consider the difference between the if and true keywords.

Conclusion

In this article, we have extensively studied whitespace in Ruby along with the basic introduction of Ruby.

After reading about the whitespace in Ruby, are you not feeling excited to read/explore more articles on the topic of Ruby? Don't worry; Coding Ninjas has you covered. See Introduction to ruby on railsDirectory Structure in RubyRuby on RailsRuby vs PythonYou can also refer to the Official Documentation and Ruby Koans .

Until then, All the best for your future endeavors, and Keep Coding. "We hope that this blog has helped you enhance your knowledge regarding this problem, and if you would like to learn more, check out our articles on  Coding Ninjas Studio.

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Conclusion

Live masterclass