Home »
Ruby »
Ruby Find Output Programs
Ruby basics – Find output programs (set 2)
This section contains the Ruby basics find output programs (set 2) with their output and explanations.
Submitted by Nidhi, on February 10, 2022
Program 1:
def main
num = 20;
msg = "Hello World"
printf "Num: %d\n", num;
printf "Message: %s\n", msg;
end
main();
Output:
Num: 20
Message: Hello World
Explanation:
In the above program, we created an integer variable num and a string variable msg. Then we printed the value of variables in a formatted manner using the printf() method.
Program 2:
def main
num = 20;
msg = "Hello World"
printf("%d,%s\n"), num, msg;
end
main();
Output:
HelloWorld.rb:5: syntax error, unexpected ',', expecting keyword_end
printf("%d,%s\n"), num, msg;
^
HelloWorld.rb:5: syntax error, unexpected ';', expecting '='
... printf("%d,%s\n"), num, msg;
... ^
HelloWorld.rb:8: syntax error, unexpected end-of-input, expecting keyword_end
main();
^
Explanation:
The above program will generate syntax errors due to the syntax of the printf() method. The correct source code is given below:
def main
num = 20;
msg = "Hello World";
printf("%d,%s\n", num, msg);
end
main();
Program 3:
ret = puts "Hello";
if ret == nil
print "ABC\n";
else
print "XYZ\n";
end
Output:
Hello
ABC
Explanation:
In the above program, we printed the "Hello" message using the puts() method. The puts() method returns nil, that's why "ABC" is also printed.
Program 4:
var1 = var2 = "hello";
print "var1: ", var1, "\n";
print "var2: ", var2, "\n";
Output:
var1: hello
var2: hello
Explanation:
In the above program, we created two variables var1, var2 that were initialized with "hello". Then we printed the value of both variables.
Program 5:
var1 = "hello ";
var2 = "hi ";
var3 = var1 + var2;
print "var3: ", var3, "\n";
Output:
var3: hello hi
Explanation:
In the above program, we created two string variables var1, var2 that were initialized with "hello ", "hi ". Then we concatenated the strings using the "+" operator and assigned the result to the variable var3. After that, we printed the result.
Ruby Find Output Programs »