Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Multiline Arithmetic in Ruby

Tags:

ruby

How to write multiline arithmetic properly in Ruby? Previously, i have tried something like y, then i realized there is something wrong with that code. I need to write multiline arithmetic due to my very long equation.

a = 5
b = 5

x = (a + b) / 2

puts x # 5, as expected

y = (
      a
      + b
    ) /
    2

puts y # 2, what happened?
like image 433
waza Avatar asked Jun 15 '14 00:06

waza


2 Answers

(
  expr1
  expr2
 )

is actually, in Ruby, the same as

(expr1; expr2)

which just executes the first expression (for side effects) and returns the second one (also after evaluating it)

like image 108
Ven Avatar answered Oct 04 '22 01:10

Ven


The Ruby parser will assume a statement has ended if it looks like it has ended at an end of the line.

What you can to do prevent that is to leave the arithmetic operator just before a new line, like this:

a = 1
b = 2
c = a + 
    b

And you'll get the result you expect.

like image 31
Maurício Linhares Avatar answered Oct 04 '22 01:10

Maurício Linhares