ADVERTISEMENT
ADVERTISEMENT

Ruby conditional statements – Find output programs (set 2)

This section contains the Ruby conditional statements find output programs (set 2) with their output and explanations.
Submitted by Nidhi, on February 11, 2022

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!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.