Page 1 of 1

comparing in Ruby

Posted: Mon Oct 13, 2014 3:39 pm
by kortezzzz
Hi, I need a simple ruby code with 2 float inputs and one float output. Ruby should then compare the 2 inputs,
and if equal, it outputs the second input's value. Other than that, it outputs 0.
Can someone shed some light? Can be a very useful tool for any one of us.

Re: comparing in Ruby

Posted: Mon Oct 13, 2014 4:08 pm
by KG_is_back

Code: Select all

def event i,v
if @ins[0]==@ins[1]
      then
           output 0,@ins[1]
      else
           output 0,0.0
      end
end


a simple if else statement.

Re: comparing in Ruby

Posted: Mon Oct 13, 2014 6:59 pm
by kortezzzz
Thanks KG, works great. Recommend anyone who doesn't knows programing in Ruby to adopt this. No doubt you'll need it one day. 8-)

Re: comparing in Ruby

Posted: Mon Oct 13, 2014 8:08 pm
by tulamide
And for those who want to dive deeper:

In short programs like these you don't need the method definition. That are structures that help you keeping overview in larger programs. Something like this, for example, just to replace some math prims, is valid without.

Also, 'then' is only needed when you write the if-expression in one line. So, you can just write

Code: Select all

if @ins[0] == @ins[1]
   output 0, @ins[1]
else
   output 0, 0.0
end


without the

Code: Select all

def event i,v
end


The magic comes in when you realize that 'if' is not a statement, but an expression. it returns a value. Therefore the following are all valid expressions of the very same action as above:

Code: Select all

@ins[1] = 0.0 if @ins[0] != @ins[1]
output 0, @ins[1]

Here you are directly manipulating the input value before sending it out.

Code: Select all

output 0, @ins[1] if @ins[0] == @ins[1]
output 0, 0.0 if @ins[0] != @ins[1]

In this context it reads as 'output @ins[1] if true, output 0.0 if false

Code: Select all

output 0, @ins[0] == @ins[1] ? @ins[1] : 0.0

This is the so called ternary operator, a short form of 'if else': test_exp ? true_exp : false_exp
Since it either returns @ins[1] or 0.0, it can be directly written as a parameter of output

Code: Select all

output 0, if @ins[0] == @ins[1] then @ins[1] else 0.0 end

The long form. And the most preferable one. And the most beautiful one :mrgreen:

I hope it helps!

Re: comparing in Ruby

Posted: Mon Oct 13, 2014 8:17 pm
by RJHollins
Thanks tulamide,

Always appreciate the education ! :D

Re: comparing in Ruby

Posted: Mon Oct 13, 2014 8:21 pm
by tulamide
You're very welcome :)

:geek:

Re: comparing in Ruby

Posted: Mon Oct 13, 2014 9:46 pm
by kortezzzz
Wow, thanks tulamide. Now i realy have to take a second look into my older clumsy green based schematics. The only thing I'v learned to love in Ruby is those naughty little time/resorces/ nerves savers that save the day (Literally).
So lately, I'v become ,reluctantly, kind of Ruby "if then" modules collector (untill i'll finally learn ruby. Or not...).
Thanks.