×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby conditional statements – Find output programs (set 2)

Last Updated : December 15, 2025

Program 1

num = 8.54;

if (num % 2 == 0)
  println("Even Number");
else
  println("Odd Number");
end

Output

HelloWorld.rb:6:in `<main>': undefined method `println' for 
main:Object (NoMethodError)
Did you mean?  print
               printf

Explanation

The above program will generate a syntax error because println is not an inbuilt function in ruby.


Program 2

num = print("hello\n");

if (num % 2 == 0)
  print("Even Number");
else
  print("Odd Number");
end

Output

HelloWorld.rb:3:in `<main>': undefined method `%' for nil:NilClass (NoMethodError)

Explanation

The above program will generate a runtime error because the print() function returns "nil" and we cannot use the "%" operator with the "nil" value.


Program 3

num = 10;

if true
  printf("Hello: %d", num);
else
  printf("Hi: %d", num);
end

Output

Hello: 10

Explanation

There is no error in this program. We can use true or false as the conditional expression.


Program 4

num = 10;

if (num == 10) == true
  printf "Hello";
else
  printf "Hi";
end

Output

Hello

Explanation

In the above program, we created a variable num initialized with 10. Then we checked the value of num in the if condition and printed the appropriate message.


Program 5

num1 = 10;
num2 = 20;
num3 = 30;
large = 0;

if num1 > num2 && num1 > num3
  large = num1;
else if num2 > num1 && num2 > num3
  large = num2;
else
  large = num3;
end

print("Largest value is : ", large);

Output

HelloWorld.rb:14: syntax error, unexpected end-of-input, expecting keyword_end
...("Largest value is : ", large);
...                               ^

Explanation

The above program will generate a syntax error because we cannot use else if in the ruby program. The correct program is given below,

num1 = 10;
num2 = 20;
num3 = 30;
large = 0;

if num1 > num2 && num1 > num3
  large = num1;
elsif num2 > num1 && num2 > num3
  large = num2;
else
  large = num3;
end

print("Largest value is : ", large);

# Output: Largest value is : 30

Ruby Find Output Programs »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.