Monday, 3 March 2014

How To Use The If conditional In Ruby

How do most computer languages evaluate and make simple decisions? Mostly through the use of the conditional 'If' statement. Whats more Ruby is no different though a lot might argue including myself a hell of a lot easier. So lets take a look at this statement in action shall we?

irb(main):001:0> age = 50
=> 50
irb(main):002:0> if age < 50
irb(main):003:1> puts('still a few years on the clock yet')
irb(main):004:1> else
irb(main):005:1* puts('too bad')
irb(main):006:1> end
too bad

First off we set assigned 50 to the age. Then we started with the conditional 'if' to evaluate the age where we used an operator < which means less than. So we said if age was less than 50 print the first message or if not print the second message.

And that's a simple way to use the conditional 'if' operator in Ruby.

How To Assign Basic Values To Variable In Ruby

Assigning Values To Variables in Ruby is a pretty easy thing to do. Once you learn it there's no end to the fun you can have with this programming language.

Here are a couple of examples as how you can manipulate variables and their values in Ruby.

irb(main):001:0> x = 50
=> 50
irb(main):002:0> y = 100
=> 100
irb(main):003:0> puts x + y

Firstly we assigned numbers to the variables x and y. Then we used the 'puts' method to output the combined value of x + y to arrive at our total of 150! Simples!