Hi , Yesterday I have started with ruby by Mr.Thyagarajan sir . Class was so interactive .
While taking class , he gave many samples .. and made us so strong in Concepts
I like to share these sample program with you 🙂
Palindrome is concept which gives output as
name = reverse(name)
Here there is method called “reverse” we can use that .. It is easy to get result compare to other language
while true print "Enter the name :" a = gets.chomp b = a.reverse if a == b puts "palindrome" else puts "not a palindrome" end end
0 . 1 , 1 , 2 . 3 , 5 , 8 ..etc
By giving level , we can get output upto to that level
if u enter “12” – output will be : 0,1,1,2,3,5,8,13
print "Enter the number :" a = gets.chomp.to_i count = 0 b = 0 c = 1 puts b , c while count<a count = b+c b = c c = count puts count end
What is Amstorng Number?
153 = 1^3 + 5^3 + 3^3
this will give same result as that .
So I am checking , a number is Amstrong number or not
print "Enter the number :" a = gets.chomp.split(//) sum = 0 for line in a c = line.to_i b = (c)*(c)*(c) sum = sum + b end if sum == a.to_s.to_i puts "Amstrong " else puts "Non amstrong" end
This will checks that , given number is Amstrong number
Next then I was taught about “Object Oriented Programing” .
A variable whose name begins with ‘@’ is an instance variable . An instance variable available only for that instance
This variable available for all the instance .. A variable whose name begins with ‘@@ is an class variable
Sample program using Class –
class Integer @@counter = 0 def recurs @@counter += 1 if @@counter<=self puts @@counter self.recurs end end end 5.recurs
This will print the value to “5” .
In this it call function from that same function . This is recursion .
Class variable and Instance variable:
class Mypurpose @@accumulator=0 def mymethod @variable1 = 10 @@accumulator = @@accumulator + @variable1 end def mysecondmethod print @variable1 print @@accumulator end end p=Mypurpose.new p.mymethod p.mysecondmethod q=Mypurpose.new q.mymethod q.mysecondmethod r=Mypurpose.new r.mymethod r.mysecondmethod