Ruby – Variables

November 12, 2009

Scenario 1: Local variable

class Ordin
def first
a=10
puts a
end
def second
puts a
end
end

obj=Ordin.new
obj.first
obj.second

output:

variable_explanation.rb:11:in `second’: undefined local variable or method `a’ for #<Ordin:0xb7d3c5e0> (NameError)
from variable_explanation.rb:17

10

Description:
a –> works only inside of first method

———————————————-

Scenario 2: Method variable

class Metho
def first
@a=10
puts “#{@a} from first method”
end
def second
puts “#{@a} from second method”
end
end

obj=Metho.new
obj.first
obj.second

output:

10 from first method
10 from second method

———————————————-

Scenario 3: Class Variable

class One
@@a=10
def first
puts “#{@@a=@@a+3} from first method”
end
def second
puts “#{@@a} from second method”
end
end

class Two < One
def third
puts @@a
end
end

obj=Two.new
obj.third

Ouput:

10

———————————————-

Scenario 4: Global Variable

class One
$a=10
def first
puts “#{$a} from first method”
end
def second
puts “#{$a} from second method”
end
end

class Two
def third
puts $a
end
end

obj=Two.new
obj.third

Ouput:

10

———————————————-

CODE.rb

code=’<html>
<head>
<title>title</title>
<meta content=”title” name=”keywords”/>
<meta content=”text/html; charset=iso-8859-1″ http-equiv=”Content-
Type”/>’

puts content= code.scan(%r{content=”(.*?)”}im).flatten[0].to_s
puts name=code.scan(%r{name=”(.*?)”}im).flatten.to_s

 

Output:

title
keywords

Ruby – Get ASCII value

October 30, 2009

Example 1:

puts ?r  #=> 114

puts ?a #=> 97

Example 2:

output=”raveendran”

puts output[0]  #=>114 ‘value of r’

puts output[1] #=> 97  ‘value of a’

Example 3:

output=”raveendran”
output.each_byte do |a|
puts a
end

>ruby ascii_from_ruby.rb
114
97
118
101
101
110
100
114
97
110
>Exit code: 0


 

Code:

def running(a)

running=`tasklist`

if running.include?(a)

puts “#{a} is already running in windows machine”

else

puts “#{a} is not running”

end

end

runnning(‘java.exe’)

#=>   java.exe is already running in windows machine

runnning(‘notepad.exe’)

#=> notepad.exe is not running

Where this code will useful:

We can able to chaeck the process is runnign or not — When Script need to close some opened Firefox windows or chrome windows

 

Code

require ‘rubygems’

require ‘win32ole’

 

def window_name_opened(name)

w=WIN32OLE.new(‘WScript.Shell’)

output=w. AppActivate(name)

puts output

end

window_name_opened(‘notepad’)

#=> false

 

Step 2 –> Now open one note pad and run the ruby program again it should returns TRUE

 

Joker – Ruby gem

September 10, 2009

Joker – Ruby gem

Good Alternate for Regular expressions

require ‘rubygems’
require ‘joker’

wild = Wildcard['Fairy?ake*']

puts wild =~ ‘Fairycake’                     #=> true
puts wild =~ ‘Fairyfakes’                    #=> true
puts wild =~ ‘Fairylake is a cool place’     #=> true

puts wild =~ ‘Dairycake’                     #=> false
puts wild =~ ‘Fairysteakes’                  #=> false
puts wild =~ ‘fairycake’                     #=> false

puts wildi = Wildcard['Fairy?ake*\?', true]

puts wildi =~ ‘FairyCake?’                   #=> true
puts wildi =~ ‘fairyfakes?’                  #=> true
puts wildi =~ ‘FairyLake IS A COOL Place?’   #=> true

Wildcard.quote(‘*?\\’)                  #=> ‘\\*\\?\\\\’

For more details about this gem –> http://bit.ly/L9kcg

Ruby – Read/Write ProxyServer details in Windows registry

Code:

require ‘win32/registry’

def get_proxy
path = ‘Software\Microsoft\Windows\CurrentVersion\Internet Settings’
type, value =     Win32::Registry::HKEY_CURRENT_USER.open(path).read (‘ProxyServer’)
puts value
end

def set_proxy
path = ‘Software\Microsoft\Windows\CurrentVersion\Internet Settings’
name=’ProxyServer’
data=’socks=34.12.78.92:54323′
type=1

Win32::Registry::HKEY_CURRENT_USER.open (path,Win32::Registry::KEY_WRITE).write(name,type,data)
end

get_proxy
set_proxy
get_proxy

Output:

socks=68.42.78.102:56773
socks=34.12.78.92:54323

Random names in Ruby

August 1, 2009

Code:

def rando
letter=(“a”..”z”).to_a
return @name=
letter[rand(letter.length)]+”#{rand(9)}”+letter[rand(letter.length)]+
letter[rand(letter.length)]+letter[rand(letter.length)]+”#          {rand(9)}”+letter[rand(letter.length)]+
letter[rand(letter.length)]+”#    {rand(9)}”+letter[rand(letter.length)]+letter[rand(letter.length)]+
letter[rand(letter.length)]+letter[rand(letter.length)]+”#{rand(9)}”
end

rando
puts @name

Output:

o1epp7yn0clbk4

Examples

Basic usage:

  ask("Company?  ") { |q| q.default = "none" }

Validation:

  ask("Age?  ", Integer) { |q| q.in = 0..105 }
  ask("Name?  (last, first)  ")
 { |q| q.validate = /\A\w+, ?\w+\Z/ }

Type conversion for answers:

  ask("Birthday?  ", Date)
  ask("Interests?  (comma sep list)  ",
lambda { |str| str.split(/,\s*/) })

Reading passwords:

  ask("Enter your password:  ") { |q| q.echo = false }
  ask("Enter your password:  ") { |q| q.echo = "x" }

ERb based output (with HighLine‘s ANSI color tools):

  say("This should be <%= color('bold', BOLD) %>!")

Menus:

  choose do |menu|
    menu.prompt = "Please choose your favorite
programming language?  "

    menu.choice(:ruby) { say("Good choice!") }
    menu.choices(:python, :perl)
{ say("Not from around here, are you?") }
  end

Reference --> http://highline.rubyforge.org/doc/
Ruby - convert number to english word

CODE :

class Fixnum
 def english_word
  @h = {0=>"zero", 1=>"One", 2=>"Two", 3=>"Three",
 4=>"Four", 5=>"Five",6=>"six", 7=>"seven", 8=>"Eight",
9=>"Nine",10=>"Ten",11=>"Eleven",12=>"Twelve",
13=>"Thirteen",14=>"Fourteen",15=>"Fifteen",
16=>"Sixteen",17=>"Seventeen",18=>"Eighteen",
19=>"Nineteen",20=>"Twenty",30=>"Thirty",
40=>"Fourty",50=>"Fifty",60=>"Sixty",70=>"Seventy",
80=>"Eighty",90=>"Ninty"}
  @i=0
  @array=[]
  @result=""a
  if self > 99
    str_num=self.to_s #@num.to_s
    str_num_len=str_num.length
    str_full_num=str_num.insert(0,"0"*(11-str_num_len))
    str_full_num=str_num.insert(8,"0")
    str_full_num.scan(/../) { |x|  @array<<x }
    6.times do
    self.def_calc
    @i+=1
    end
  else
     if self > 9
        puts
(self.proc_double_dig((self/10)*10))+
(self.proc_single_dig(self%10))
     else
       if self > 0
       puts self.proc_single_dig(self)
       else
        return "AMOUNT NOT KNOWN or NILL"
       end
     end
  end
  end

  def def_calc
    case @i
      when 0
        str=self.proc_unit(@array[@i])
        if (str.scan(/\w+/)).length!=0
             then str=str+ "hundred & "
              @result=@result+str
        end
      when 1
        str=self.proc_unit(@array[@i])
        if (str.scan(/\w+/)).length!=0
             then str=str+ " Crore, "
             @result=@result+str
        end
      when 2
        str=self.proc_unit(@array[@i])
        if (str.scan(/\w+/)).length!=0
             then str=str+ " Lakh, "
             @result=@result+str
        end
      when 3
        str=self.proc_unit(@array[@i])
        if (str.scan(/\w+/)).length!=0
             then str=str+ " Thousand, "
             @result=@result+str
        end
      when 4
        str=self.proc_unit(@array[@i])
        if (str.scan(/\w+/)).length!=0
             then str=str+ " Hundred, "
             @result=@result+str
        end
      when 5
        str=self.proc_unit(@array[@i])
        if (str.scan(/\w+/)).length!=0
             then str=str+ ". "
             @result=@result+str
        end
        print @result.sub(/..$/,"")
    else
   end
  end

  def proc_unit(x)
    if x.to_i>0
      if x.to_i<=10
        return self.proc_single_dig(x.to_i)
      else
        if x.to_i<=20
        return self.proc_double_dig(x.to_i)
        else
        return
(self.proc_double_dig((x.to_i/10)*10))+
(self.proc_single_dig(x.to_i%10))
        end
     end
    end
  return ""
  end

  def proc_double_dig(z)
    if z==0
      return ""
    else
      return @h[z]
    end
 end

  def proc_single_dig(y)
    if y==0
      return ""
    else
      return @h[y]
    end
  end
protected :def_calc, :proc_unit, :proc_double_dig,
  :proc_single_dig

end

puts 453645445.english_word

#FourtyFive Crore, Thirtysix Lakh, FourtyFive Thousand,
Four Hundred,FourtyFive

Note:
The above code works only up to billions.