Tuesday, 31 January 2017

Replace string using Ruby sub function

Usually in shell script we have wonderful text process tools like sed, awk similar options I want to explore in the Ruby scripting. Here we go with small sample where the script will input a text string. then sub is a built-in function  in Ruby will replaces the string. The syntax of sub looks like vi command mode replace option.

Snippet:

puts "This program will replace your string"

print "Enter a string: "
user_input = gets.chomp

if user_input.length > 0
        user_str = user_input
        rplcd_str = user_input.sub(/#{user_str}/,'Voila!')
        puts "Your String: #{user_str} Replaced with: "
else
        puts "Please enter a valid string!\n"
end

Execution:

ruby test.rb
This program will replace your string
Enter a string: Sunil
Your String: Sunil Replaced with: Voila!

Saturday, 3 December 2016

Ruby loops examples

Ruby Programming Loops

Ruby also provides different types of loops like  other programming languages does. But its syntax quiet different and also multiple options you can see for the loop constructs.

While and until loops in Ruby


While loop

Ex: Printing 1 to 10 numbers




Ex;2
while
#script to find factorial of a given number

puts "enter the number"
x=gets.chomp.to_i 
fact=1
while x > 0
fact= fact * x
x -= 1
end
puts "the factorial for given number is #{fact}"


Output:

E:\Ruby>ruby factorial.rb
enter the number
5
the factorial for given number is 120


Few challenges were found while executing this script.
factorial.rb:6:in `>': comparison of String with 0 failed (ArgumentError) from factorial.rb:6:in `


 it was troubleshooted by adding "chomp.to_i" method to gets method to convert given number into integer Most important lesson: read the error messages. Ruby failed to compare a number to a string because they are just incompatible data types: it's nonsensical to ask what is bigger: "abc" or 123. And gets.chomp always gives you a String (something like "4", which is not the number 4). So in order to compare the user's input to a number, you have to convert it to a number first: Ruby Strings have the .to_i (to integer) method for this
until

for loop

for
each loop
each do 

  This loop stops execution when condition becomes false

Wednesday, 23 November 2016

4 Initializing instances

Using initialize methods can make objects usage in safer manner..
class Account
        def ac_deposit(d)
                @balance=10000
                @balance=@balance+d
        end
        def withdraw(a)
                @balance-=a
        end

        def show_bal
                puts "\tCurrent balance: #{@balance}"
        end
end

currentAC=Account.new
amt=200
puts "\ndeposit #{amt}"
currentAC.ac_deposit(amt)
currentAC.show_bal

amt=2000
puts "\nWithdraw #{amt}"
currentAC.withdraw(amt)
currentAC.show_bal
In Ruby Class object instance

Tuesday, 22 November 2016

Object-oriented Ruby : Inheritance

This is first time I've experiencing Object-orient scripting language. Enjoying inheritance parent-child relationships in the programming. It can be defined as sharing methods between classes. it avoids copynjing and pasting of same kind of methods and variables. Inheritance has two concepts which are Super class and subclass. Let me share my Example:
     class Vechile
         def accelrate
           puts "floor it"
         end

         def horn
           puts "blow blow"
         end
      end

     class Car < Vechile
     end

 vechile=Car.new
 vechile.accelrate
 vechile.horn
I've issue with my Linux box so I've installed on Windows.
C:\Users\JITTA>ruby -version
ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32]
-e:1:in `
': undefined local variable or method `rsion' for main:Object (NameError)
Let's start irb interactive mode:
C:\Users\JITTA>irb -I
irb(main):001:0> class Vechile
irb(main):002:1>          def accelrate
irb(main):003:2>            puts "floor it"
irb(main):004:2>          end
irb(main):005:1>
irb(main):006:1*          def horn
irb(main):007:2>            puts "blow blow"
irb(main):008:2>          end
irb(main):009:1>       end
=> :horn
irb(main):010:0>
irb(main):011:0*      class Car < Vechile
irb(main):012:1>      end
=> nil
irb(main):013:0>
irb(main):014:0*  vechile=Car.new
=> #
irb(main):015:0>  vechile.accelrate
floor it
=> nil
irb(main):016:0>  vechile.horn
blow blow
=> nil
irb(main):017:0>
The "super" keyword is used to get the parent attributes into derived class.
irb(main):001:0> class Person
irb(main):002:1>   def greeting
irb(main):003:2>     puts "hello"
irb(main):004:2>    end
irb(main):005:1> end
=> :greeting
irb(main):006:0> class Friend < Person
irb(main):007:1>    def greeting
irb(main):008:2>    super
irb(main):009:2>     puts "glad to see you!"
irb(main):010:2>     end
irb(main):011:1> end
=> :greeting
irb(main):012:0> Friend.new.greeting
hello
glad to see you!
Without Super keyword
irb(main):013:0>  class Person
irb(main):014:1>    def greeting
irb(main):015:2>      puts "hello"
irb(main):016:2>     end
irb(main):017:1> end
=> :greeting
irb(main):018:0> class Friend < Person
irb(main):019:1>   def greeting
irb(main):020:2>     puts "glad to see you"
irb(main):021:2>    end
irb(main):022:1> end
=> :greeting
irb(main):023:0> Friend.new.greeting
glad to see you
=> nil
irb(main):024:0>
The Object class The uncreated super class of a class untill it is created as subclass is said to be Object class Example:
           class Unix       /*Object class*/
              def kernal
                  puts "The unix kernal is  different to linux"
               end
               def vendor

                  puts "Unix has diffrent vendors like ibm,hp and oracle"
               end
          end
          class Solaris <  Unix   /*Super class*/
                 end
           os=Solaris.new
           os.kernal
           os.vendor
     
One more experiment with the inheritance
irb(main):001:0>
irb(main):002:0*            class Unix
irb(main):003:1>               def kernal
irb(main):004:2>                   puts "The unix kernal is  different to linux"
irb(main):005:2>                end
irb(main):006:1>                def vendor
irb(main):007:2>
irb(main):008:2*                   puts "Unix has diffrent vendors like ibm,hp and oracle"
irb(main):009:2>                end
irb(main):010:1>           end
=> :vendor
irb(main):011:0>           class Solaris <  Unix
irb(main):012:1>                  end
=> nil
irb(main):013:0>            os=Solaris.new
=> #
irb(main):014:0>            os.kernal
The unix kernal is  different to linux
=> nil
irb(main):015:0>            os.vendor
Unix has diffrent vendors like ibm,hp and oracle
=> nil
In Ruby script why everything inherit from the Object class? Because the Object class provides useful methods which needed by every Ruby object like
 1 to_s       /*converts an object to a string for printing   /
 2 inspect
 3 class
 4 methods
 5 instance_variables

Thursday, 17 November 2016

Ruby classes methods

Methods in Ruby:

Ruby methods are used to bundle one or more repeatable statements into single unit

Syntax:

    def methodname

        statement1
        statement 2
         ,,,,,,,,,,,,,,,,,

   end


Example:

def Systeminfo(a,b,c)
  puts "The ram size is #{a}"
  puts "The hard disk info  is  #{b}"
  puts "The OS type is #{c}"
end

Systeminfo("4GB","400GB","Centos")

Output:



Class

A class is blueprint for  making objects.When we use a class to make an object, the class describes what object knows about itself, as well as what object does.

Ruby Object

An object is an instance which has set  of  data and methods which operate on that data  in one place

Advantages of Class


  1. Puts data at single unit
  2. Reduces the complexity
  3. Makes programmer easier


Syntax:

 class Classname
   def mehtod1
     statement1
     statement2
     ,,,,,,,,,,,,,,,n
   end
   def metod2
     statement1
     statement2
     ,,,,,,,,,,,,,,,,n
   end
end


Example:

   class Account
     def ac_deposit(d)
       @balance=10000
        @balance=@balance+d
      end
      def withdraw(a)
        @balance=a
      end

     def show_bal
        puts "Current balance: #{@balance}"
     end
end

currentAC=Account.new
currentAC.ac_deposit(500)
currentAC.show_bal
currentAC.withdraw(2000)
currentAC.show_bal

 



     

Saturday, 29 October 2016

Introduction to Ruby

This is my scripting blog where I am doing experiments and learning. In this I might encounter some of the errors and how I've resolved them by understanding by reading "HeadFirt Ruby" book. I really love to read this book which helped me to give strengthen my programming skill. When I got to some conclusion I will execute it and then move forward on the concept. So here my first day experiments with Ruby.

Why Ruby scripting for DevOps?


I did little search on the google trends what all tools used in configuration management found the following:

  • Chef
  • Puppet
  • Ansible
  • SaltTalk

There are different tools at varety of reasons, all of them are looking for the scripting language that could be a definative way of expressing. They all need client-server model but fastest communicatiive way. Better way of  memory management by itself. writing could be as easy as possible.

Configuration Tool analysis on recent demand 

Anyway my learning of Ruby script is justified by the above trends in demand currently. Lets do this and progress towards success in DevOps tools easily.

My list of understanding topics are :

  1. Math Arithmetic operators
  2. comparison operators
  3. String usage



Math operators in Ruby

Here I am experimenting with some of the operators that does simple calucations. I've opened an irb shell to execute these operations.
irb(main):001:0> 5.4 - 3
=> 2.4000000000000004
irb(main):002:0> 3 * 4
=> 12
irb(main):003:0> 7 / 3
=> 2
irb(main):004:0> 7.0 / 3
=> 2.3333333333333335
irb(main):005:0> 7.0 3
SyntaxError: (irb):5: syntax error, unexpected tINTEGER, expecting end-of-input
        from /bin/irb:12:in `
' irb(main):006:0> 7.0/3 => 2.3333333333333335 irb(main):007:0> 2**3 => 8 irb(main):008:0> 4**9 => 262144 irb(main):009:0> 1.4***3 SyntaxError: (irb):9: syntax error, unexpected * 1.4***3 ^ from /bin/irb:12:in `
' irb(main):010:0> 1.4***3 SyntaxError: (irb):10: syntax error, unexpected * 1.4***3 ^ from /bin/irb:12:in `
' irb(main):011:0> 1.4**3 => 2.7439999999999993 irb(main):012:0> 4<6> true irb(main):013:0> 21 => 21 irb(main):014:0> 2ge5 SyntaxError: (irb):14: syntax error, unexpected tIDENTIFIER, expecting end-of-input from /bin/irb:12:in `
' irb(main):015:0> 4<=2 => false irb(main):016:0> 1+2==4 => false irb(main):017:0> 1+2==3 => true 
Now how to use your Ruby variable got some idea. Then you goto develop the Ruby script I will not use such syntaxError.

Strings in Ruby

I am here to expose when we do mistakes in Ruby scripting, why we are here to get this. To cope up with multipe devops problems and get the solutions with Ruby but to began or conclude something we need strings.

irb(main):027:0> name x
NoMethodError: undefined method `name' for main:Object
        from (irb):27
        from /bin/irb:12:in `
' irb(main):028:0> x => 3 irb(main):029:0> name | x NoMethodError: undefined method `|' for "hari":String from (irb):29 from /bin/irb:12:in `
' irb(main):030:0> name and x => 3 irb(main):031:0> x=3 => 3 irb(main):032:0> y=4 => 4 irb(main):033:0> x+y => 7 irb(main):034:0> y+=1 => 5 irb(main):035:0> x-=2 => 1 irb(main):036:0> name +="jitta" => "harijitta"

My interactive ruby commands failed sometimes it is not good but I learnt what can be string type objects better way to use them in the scripting.