MainMenu

Home Java Overview Maven Tutorials

Thursday, 23 August 2018

Basic Programs in Ruby

Basic Programming in ruby



Basic Programming in Ruby :-


0). How to print something in Ruby :-

print 'welcome to ruby'
puts 'hello ruby'
puts "hello again ruby"


Output :-welcome to rubyhello ruby
hello again ruby
Note :puts will change the row, but print will not.

--------------------------------------------------------------
1). Arithmatic Operator :-
Always remember ruby is case senstive.

x = 10
y =20
z = x+y
puts z
z = x*y
puts z
z = x-y
puts z
z = y/z
puts z

Output :-
30
200
-10
-2
--------------------------------------------------------------

2). If Else loop in ruby :-

x = 10
y = 20
if x>y
puts "x is greater than y"
else
puts "y is greater than x"
end

Output :-x is greater than y
-------------------------------------------------------------
3). While & Do while loop in ruby :-

x = 10
y = 20
while x<y do
x = x+1;
print "value of x is"
puts x
end



In the below code first value of x will be incremented and then printed after that condition will be checked

x = 10
y = 20
begin
x = x+1
puts x
end while x

Output in both the code:-
11
12
13
14
15
16
17
18
19
20
------------------------------------------------------
4).For Loop & for loop with break :-

for i in 0..5
puts i
end



Output :-
0
1
2
3
4
5

For loop with break statement

for i in 0..5
if i>2 then
break
end
puts i
end

Output :-
0
1
2


Next Topic :- Basic Programming in ruby Array, String & Methods etc

Previous Topic :- How to download and install Ruby & Rubymine

No comments:

Post a Comment