Tuesday, 23 December 2014

xpaths

First Row in a table:FIrst row is having class=odd

     $x("//tr[1][@class='odd']")

hyperlink in first row of a table:

     "//tr[1][@class='odd']/td[2]/a"  or    
     $x("//table/tbody/tr[1][@class='odd']/td[2]/a")    whole hierarchy.. test it in firebug console 

WebTable _selenium webdriver using Ruby code so far developed.. Minispec used to validate text

require_relative '../../lib/Element.rb'
require_relative '../../lib/Link.rb'
require_relative '../../lib/TextBox.rb'
require_relative '../../lib/ComboBox.rb'
require_relative '../../../features/util/ExpectedElements'
require 'selenium-webdriver'
require 'rspec'
require 'rspec/expectations'


class OrdersMainPage
# Initializing the page object for Login page
  def initialize
    # Declaring page objects
    @linkAllOrders= Link.new(:css, "#orders-list-all")
    @linkReserved= Link.new(:css, "#orders-all-reserved")
    @linkCancelled= Link.new(:css, "#orders-all-cancelled")
    @linkApproved= Link.new(:css, "#orders-all-approved")
    @linkUnfulfilled= Link.new(:css, "#orders-all-unfulfilled")
    @linkShipping= Link.new(:css, "#orders-all-shipping")
    @linkReturnStatus= Element.new(:xpath, "//span[contains(text(), 'Orders by Return Status')]")
    @linkNone= Link.new(:css, "#orders-all-none")
    @linkPartReturned= Link.new(:css, "#orders-all-partreturned")
    @linkReturned= Link.new(:css, "#orders-all-returned")

    #Middle Pane Orders Page
    @linkStatusFilter= ComboBox.new(:id, "status")
    @linkChannels= Link.new(:css, "#btn btn-default dropdown-toggle")
    @linkDateFilter= Element.new(:css, "div#reports-daterangepicker")
    @linkSearch= Element.new(:css, "i[class='fa fa-search']:first-child")
    @linkProducts= Link.new(:css, "a[data-test='menuHeaderCatalogue'")

    @tableOrders=Element.new(:xpath, "//table[@id='DataTables_Table_0']")
    @elementRightNavigate=Element.new(:css, "i[class='fa fa-long-arrow-right']")

    # @defaultSearchFields = ExpectedElements.new(@allOrders, @reserved, @cancelled)
  end

  def getOrderData(order_id)
    #"//a[contains(text(), '3466')]"
    puts "get order data function inside #{order_id}"
    @order_row=nil
    iterateTable=1
    iRow=1

    #if an order doesn't exits then navigate to next page. iterate 3 times
    while iterateTable<=5
      #check for the order link in the page
      if existsElement(:xpath, "//a[contains(text(), '" + order_id + "')]")
        break
      else
        @elementRightNavigate.clickObj
        iterateTable=+1
      end
    end

    begin
      #get row count
      table=$browser.find_element(:xpath, "//table[@id='DataTables_Table_0']/tbody")
      iRows= table.find_elements(:tag_name, "tr")
      rowSize=iRows.length
      # puts   "row size is : #{rowSize}"

      #get row with cell text
      rows=$browser.find_elements(:xpath, "//table[@id='DataTables_Table_0']/tbody/tr")
      rows.each do |rw|
        if rw.text.include?(order_id.to_s)
          @order_row=$browser.find_element(:xpath, "//table[@id='DataTables_Table_0']/tbody/tr[" + iRow.to_s + "]")
          break
        end
        iRow=iRow+1
      end

      # get Cells data into an array
      unless @order_row.nil?
        a= Array.new(4)
        cells= @order_row.find_elements(:tag_name, "td")
        @cellData = Array.new(cells.length-1)
        i=0
        cells.each do |cell|
          # puts cell.text
          @cellData[i]= cell.text
          i=i+1
        end
      end

    rescue Exception => e
      e.message
    end
    @cellData
  end

  def  OrdersPageValidation
    begin
      @linkAllOrders.getText.must_include 'All Orders'
      @linkReserved.getText.must_include 'Reserved'
      @linkCancelled.getText.must_include 'Cancelled'
      @linkApproved.getText.must_include 'Approved'
      @linkUnfulfilled.getText.must_include 'Awaiting'
      @linkShipping.getText.must_include 'Shipping'

      @linkReturnStatus.getText.must_include 'Orders by Return Status'
      @linkNone.getText.must_include 'None'
      @linkPartReturned.getText.must_include 'Part Returned'
      @linkReturned.getText.must_include 'Returned'
    rescue Exception => e
        e.message
    end
  end

  def orderDataValidation(orderData, table)
    begin table.hashes.each do |hash|
      #rspec validations
      orderData.to_s.must_include (hash['order_id'].to_s)
      orderData.to_s.must_include (hash['retailer_order_id'].to_s)
      orderData.to_s.must_include (hash['Channel'].to_s)
      orderData.to_s.must_include (hash['customer_name'].to_s)
      orderData.to_s.must_include (hash['quantity'].to_s)
      orderData.to_s.must_include (hash['price_paid'].to_s)
      orderData.to_s.must_include (hash['status'].to_s)
      end
    end
  end


  def existsElement(by, value)      #use elementExist instead..
    flag=false
    begin
      if $browser.find_element(by, value).displayed?
        flag=true
      end
    rescue Exception
    ensure
      return flag
    end
  end

  #get first order item row data into an array
  def getFirstOrderData()
    @firstRow=$browser.find_element(:xpath, "//table[@id='DataTables_Table_0']/tbody/tr[1]")
    cells= @firstRow.find_elements(:tag_name, "td")
    cellData = Array.new(cells.length-1)
    i=0
    cells.each do |cell|
      # puts cell.text
      cellData[i]= cell.text.to_s.strip
      i=i+1
    end
    cellData
  end
  #get the first order data and validate its status based on filter criteria
  def ordersFilterByStatus(table)
    begin table.hashes.each do |hash|
      @status= hash['status'].to_s.downcase.strip
      @linkStatusFilter.selectByText(hash['status'].to_s)
      sleep 3
      #get the first row order item data and compare with the parameter..
      cellData= getFirstOrderData
      unless @status.include?('return') || @status.include?('none')
        puts cellData[7]
        cellData[7].to_s.downcase.strip.must_equal (@status)     #check for Status column
      else
        puts cellData[8]
        cellData[8].to_s.downcase.strip.must_equal (@status)  #check for Return Status column
      end
      end
    end
  end


end       #end of the class

Monday, 22 December 2014

WebTable getRowwithText, rowcount, getcell data in selenium webdriver using ruby

 def getOrderData(order_id)
    #"//a[contains(text(), '3466')]"
    puts "get order data function inside #{order_id}"
    @order_row=nil
    iterateTable=1
    iRow=1

    #if an order doesn't exits then navigate to next page. iterate 3 times
    while iterateTable<=5
      #check for the order link in the page
      if existsElement(:xpath, "//a[contains(text(), '" + order_id + "')]")
        break
      else
        @elementRightNavigate.clickObj
        iterateTable=+1
      end
    end

    begin
      #get row count
      table=$browser.find_element(:xpath, "//table[@id='DataTables_Table_0']/tbody")
      iRows= table.find_elements(:tag_name, "tr")
      rowSize=iRows.length
      # puts   "row size is : #{rowSize}"

      #get row with cell text
      rows=$browser.find_elements(:xpath, "//table[@id='DataTables_Table_0']/tbody/tr")
      rows.each do |rw|
        if rw.text.include?(order_id.to_s)
          @order_row=$browser.find_element(:xpath, "//table[@id='DataTables_Table_0']/tbody/tr[" + iRow.to_s + "]")
          break
        end
        iRow=iRow+1
      end

      # get Cells data into an array
      unless @order_row.nil?
        a= Array.new(4)
        cells= @order_row.find_elements(:tag_name, "td")
        @cellData = Array.new(cells.length-1)
        i=0
        cells.each do |cell|
          puts cell.text
          @cellData[i]= cell.text
          i=i+1
        end
      end

    rescue Exception => e
      e.message
    end
    @cellData
  end


def existsElement(by, value)      #use elementExist instead..
    flag=false
    begin
      if $browser.find_element(by, value).displayed?
        flag=true
      end
    rescue Exception
    ensure
      return flag
    end
  end

Saturday, 13 December 2014

Ruby Cucumber - table data and parametrization

Scenario

 @test Scenario Outline: Testing for table and data
  Given I login with data <credentials>
  Then I test with data
    |first_name|last_name|middle_name|dob          |mobile_no |    |vicky     |G     |venu       |XXXXXXXX   |99xxxxxxxx    |  And I log out successfully

  Examples:  |credentials         |  |"myusername,mypassword"|

Step Definition:

Given(/^I login with data "([^"]*)"$/) do |credentials|
  puts credentials.class
  if credentials.include?(',')
    @arr_data=credentials.split(',')
    puts 'username is: '+ @arr_data[0]
    puts 'password is: '+ @arr_data[1]
  endend

Then(/^I test with data$/) do |table|
  begin  table.hashes.each do |hash|
     puts "first_name: #{hash['first_name']}"     puts "last_name: #{hash['last_name']}"     puts "middle_name: #{hash['middle_name']}"     puts "dob: #{hash['dob']}"     puts "mobile_no: #{hash['mobile_no']}"  end  rescue Exception=> e    puts e.message
  end
end
And(/^I log out successfully$/) do  pass
end

+++++++++++++++++Output++++++++++++++++++++

String

username is: myusername
password is: mypassword

first_name: vicky
last_name: gopi
middle_name: venu
dob: 09021986
mobile_no: 99xxxxxxxx

Ruby and Cucumber Basic example- Basic input, table and data

Feature: Cucumber basics using Ruby

@portalScenario: Sum example
   Given I add "4+8"
   And Sum should be "6"

  @test  Scenario Outline: Sum example for multiple values
   Given I add for <vals>
   And Sum should be <answer> for <vals>

Examples:   
|vals |answer|   
|"2+4"|"6"  |   
|"4+4"|"9"  |   
|"4+5"|"9"  |   
|"4+0"|"199"|

@test   
Scenario: Testing for multiple data at each step
Given I validate product feed for the details
    |username     |vickyvenu81@gmal.com  |      
    |profile       |venu                 |      
    |emp_id         |739                 |      
    |project        |bankofamerica       |     
And print pass or fail
    |col1       |col2  |     
    |data1   |data2 |     
    |data3   |data4 |
     

++++++++++++++++Step Definitions+++++++++++++++++++++++++++
Given(/^I add "([^"]*)"$/) do |arg|
  @sum= eval(arg)
end
And(/^Sum should be "([^"]*)"$/) do |arg|
  puts @sum  if @sum.to_i != 6    puts "fail"  else    puts "pass"  endend
Given(/^I add for "([^"]*)"$/) do |vals|
  @sum= eval(vals)
end
And(/^Sum should be "([^"]*)" for "([^"]*)"$/) do |answer, vals|
  puts 'sum = '+ @sum.to_s
  if @sum!=answer.to_i
    puts 'error in evaluating sum and sum should be: '+ @sum.to_s
  endend

Given(/^I validate product feed for the details$/) do |table|
  # table is a table.hashes.keys # => [:username, :password, :profile, :logout, :items_count]  puts '+++++++++++++++++++++++++++++++++++++++++++'  data = table.rows_hash
  puts data['emp_id']   #Here we are accesing row wise.. |property| value|  this will print 739end
And(/^print pass or fail$/) do |table|
  puts "table.class:-  #{table.class}"  puts 'table inspection:'  puts table.inspect

  table.hashes.each do |hash|
    puts "col1 data should be printed: #{hash['col1']}"    puts "col2 data should be printed: #{hash['col2']}"  end
  puts 'table.raw example: '  data= table.raw
  puts data[0]

end

+++++++++++++++++++++Output++++++++++++++++++++++++++++++++
C:\Ruby193\bin\ruby.exe -EUTF-8 -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:\Ruby193\bin/cucumber C:/RnD/features/gmail.feature --format Teamcity::Cucumber::Formatter --expand --color -r features
Testing started at 20:17 ...
Tag: @@portal

12

fail
Tag: @@test

Given I add for <vals>                          # features/step_definitions/gmailtest.rb:14

And Sum should be <answer> for <vals>           # features/step_definitions/gmailtest.rb:18

sum = 6

sum = 8

error in evaluating sum and sum should be: 8

sum = 9

sum = 4

error in evaluating sum and sum should be: 4
Tag: @@test

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

739

table.class:-  Cucumber::Ast::Table

table inspection:


  |     col1  |     col2  |
  |     data1 |     data2 |
  |     data3 |     data4 |

col1 data should be printed: data1

col2 data should be printed: data2

col1 data should be printed: data3

col2 data should be printed: data4

table.raw example: 

["col1", "col2"]
6 scenarios (6 passed)
12 steps (12 passed)
0m0.181s

Process finished with exit code 0

+++++++++++++++++++++++Explanation++++++++++++++++++++++++

# http://www.ruby-doc.org/gems/docs/d/davidtrogers-cucumber-0.6.2/Cucumber/Ast/Table.html# Step Definitions that match a plain text Step with a multiline argument table will receive it as an instance of Table.# A Table object holds the data of a table parsed from a feature file and lets you access and manipulate the data in different ways.#                                                                                                                                  Given I have:# | a | b |# | c | d |# This will store [['a', 'b'], ['c', 'd']] in the data variable.## hashes()# Converts this table into an Array of Hash where the keys of each Hash are the headers in the table.# For example, a Table built from the following plain text:## | a | b | sum |# | 2 | 3 | 5   |# | 7 | 9 | 16  |# Gets converted into the following:## [{'a' => '2', 'b' => '3', 'sum' => '5'}, {'a' => '7', 'b' => '9', 'sum' => '16'}]## raw: Gets the raw data of this table. For example, a Table built from the following plain text:# rows_hash: Converts this table into a Hash where the first column is used as keys and the second column is used as values## | a | 2 |# | b | 3 |# Gets converted into the following:# {'a' => '2', 'b' => '3'}

Tuesday, 2 December 2014

PWatir page object model links

All the questions and answers related to pom :
https://github.com/cheezy/page-object/issues/255  for a table.. good one


issues related to page objects and answers:
https://github.com/cheezy/page-object/issues

really good one..



http://www.cheezyworld.com/2011/07/29/introducing-page-object-gem/

https://github.com/watir/watir-webdriver/wiki/Page-Objects

Sunday, 23 November 2014

Reading XML, updaing it, Attributes content in Ruby using nokogiri xpath

require 'nokogiri'$imgNode= "<METADATA order=\"22\" key=\"Key22\"><![CDATA[2 cm]]></METADATA>"class ReadXMLNodes  def initialize()
    @file = File.open('../Orders/ShoeTemplate.xml')
    @xmlObj= Nokogiri::XML(@file)
    puts @xmlObj.to_s
    puts 'Node Count: '+ @xmlObj.xpath('//PRODUCT/P_NR').count.to_s
  end
  def getNode(strNodeXPath)
     @xmlObj.xpath(strNodeXPath)
  end
  def saveXML()
    @timeStamp= Time.new
    timestmp= @timeStamp.strftime("%Y-%m-%d-%H-%M-%S-%s")
    File.delete('../Results/FileOutput'+ timestmp+ ".xml") if File.exist? ('../Results/FileOutput'+ timestmp+ ".xml")
    @fileWr=File.new('../Results/FileOutput'+ timestmp+ ".xml", "w")
    @fileWr.write(@xmlObj.to_xml)
    @fileWr.close
  end
  def getFirstNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).first()  #Or    # @xmlObj.xpath(strNodeXPath)[0]  end
  def getLasttNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).last()  #Or    # @xmlObj.xpath(strNodeXPath)[0]  end
  def readFirstNodeContent(strXpath, strAttrVal)
    # @xmlObj.xpath("//P_ACTIVE[@channel='"+ strAttrVal + "']")[0].content    @xmlObj.xpath(strXpath + "'"+ strAttrVal + "']")[0].content  #If we dont keep content here, it reads the whole node value  end
  def readLastNodeContent(strXpath, strAttrVal)
    # @xmlObj.xpath("//P_ACTIVE[@channel='"+ strAttrVal + "']")[0].content    @xmlObj.xpath(strXpath + "'"+ strAttrVal + "']").last().content  #If we dont keep content here, it reads the whole node value  end
  def readNodeContent(strXpath, index)
    # @xmlObj.xpath(strXpath).last().content    @xmlObj.xpath(strXpath)[index.to_i].content
  end
  def removeNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).remove
  end  def removeFirstNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath)[0].remove
  end  def removeLastNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).last().remove
  end
  def countNodes(strXpath)
    @xmlObj.xpath(strXpath).count
  end
  def modify_node_content(strXpath, strValue)
    @xmlObj.xpath(strXpath)[0].content=strValue  end
  def AddNode(strXpath, strNode, index)
    if @xmlObj.xpath(strXpath).count >= 0      @xmlObj.xpath(strXpath)[index].add_next_sibling(strNode)
    end  end
  def getAttributeValue(strXpath, strAttribute)
    node= @xmlObj.xpath(strXpath)[0]
    node.attributes[strAttribute].value
  end  def modify_attribute_val(strXpath, strAttribute, val_to_assign)
    node= @xmlObj.xpath(strXpath)[0]
    node.attributes[strAttribute].value=val_to_assign  endend

readNodes= ReadXMLNodes.new
puts 'First Node is: '+ readNodes.getFirstNode('//A_MEDIADATA/A_MEDIA')
puts 'Last Node is: '+ readNodes.getLasttNode('//A_MEDIADATA/A_MEDIA')
puts 'Convert to xml: '+ readNodes.getLasttNode('//A_MEDIADATA/A_MEDIA').to_xml

# puts 'Read Node: '+ readNodes.getNode('//P_METADATA/METADATA')# puts 'Remove Node: '+ readNodes.removeNode('//P_METADATA/METADATA')# puts 'Read Node: '+ readNodes.getNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ First Read+++++++++++++++++++++++++++'puts readNodes.getNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ Remove Node +++++++++++++++++++++++++++'puts readNodes.removeLastNode('//P_METADATA/METADATA')
puts readNodes.removeNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ Read After +++++++++++++++++++++++++++'puts readNodes.getNode('//P_METADATA/METADATA')
puts readNodes.readFirstNodeContent('//P_ACTIVE[@channel=', 'tiau')
puts readNodes.readLastNodeContent('//A_PRICEDATA/A_PRICE[@channel=', 'tiau')
puts readNodes.readLastNodeContent('//A_MEDIADATA/A_MEDIA[@type=', 'image')
puts 'Print Node content'puts readNodes.readNodeContent("//A_MEDIADATA/A_MEDIA[@type='image']", 4)

print "Counting Nodes: "puts readNodes.countNodes("//A_MEDIADATA/A_MEDIA")
puts readNodes.modify_node_content("//P_ACTIVE[@channel='tiau']", "Venu Gopi")
puts readNodes.modify_node_content("//ARTICLEDATA/ARTICLE/A_NR", "999999")
puts "testing"puts readNodes.AddNode('//A_MEDIADATA/A_MEDIA', $imgNode, 4)
puts 'reading attribute value'puts readNodes.getAttributeValue('//P_ACTIVE', 'channel')
puts 'modify attribute value: 'readNodes.modify_attribute_val('//P_ACTIVE', 'channel', 'AttributeValChanged')
print 'Changed attribute value is: 'puts readNodes.getAttributeValue('//P_ACTIVE', 'channel')
puts readNodes.saveXML

=begin1. Add Nodes2. Add Attribute3. Modify Attribute4. Remove Attribute5. Read Attribute value6.=end

Tuesday, 11 November 2014

String Methods in Ruby


@s1= "This is Ruby Programming language!!"
@str2= "This is Ruby progRAMMING LANGguage.."
puts @s1.chop       #This is Ruby Programming language!
puts @s1.chomp("..")    #This is Ruby Programming language

puts @str2.count("i") #Counts one or more sets of characters.   output=3
puts @str2.count("P") #output= 1
puts @str2.count("p") #output= 0

puts @str2.downcase
puts @str2.upcase
puts @str2.capitalize
puts @str2.swapcase
puts "++++++++++++=empty? and nil? eg+++++++++++++++++++"
@s3=''
@s4='s'
sn=nil
puts @s3.nil?   #false
puts sn.nil?    #true
puts @s3.empty? #true
puts @s1.empty?   #false
puts "++++++++++++=length eg+++++++++++++++++++"
puts @s3.length
puts @s4.length
puts @str2.length

# Testing for presence of substring
puts "++++++++++++=include eg+++++++++++++++++++"
puts @s4.equal? (@s3)
puts @str2.include?("PROGRAMMING")    #case sensitive
puts @str2.include?("ruby")        #case sensitive
puts @str2.include?("LANG") #case sensitive

puts "++++++++++++=index eg+++++++++++++++++++"
@str2= "This is Ruby progRAMMING LANGguage.."
puts @str2.index("ruby").nil?  #if search string is not found, returns nil..
puts @str2.index("T") #0
puts @str2.index("his")  # 1
puts @str2.index('L',3)       # => 3: index of first l in string at or after position 3
puts "@str2.rindex('g'):  #{@str2.rindex('g')}"        # => 3: index of rightmost l in string- ge..
puts "@str2.rindex('T',2):  #{@str2.rindex('T',2)} "     # => 2: index of rightmost T in string at or before 2
puts "@str2.rindex('i',4):  #{@str2.rindex('i',4)} "     # => 2: index of rightmost i in string at or before 4.
# #checks within first 4 characters..

puts @str2.inspect      #"This is Ruby progRAMMING LANGguage.."
puts "++++++++++++=strip eg+++++++++++++++++++"
s5= "       s5Left"
s6= "s6Right             "
s7= "  s7Both      "

puts "before striping the strings, their lengths are- S5: #{s5.length}, s6: #{s6.length} and s7: #{s7.length}"
puts s5.lstrip.inspect + " and its length after lstrip #{s5.lstrip.length}"
puts s6.rstrip.inspect + " and its length after rstrip #{s6.rstrip.length}"
puts s7.strip.inspect + " and its length after lstrip #{s7.strip.length}"

#inspect method gives the printable verison of a string as: "s7Both" \
puts "++++++++++++=slice eg+++++++++++++++++++"
# slice: Deletes the specified portion from str, and returns the portion deleted. returns nil if not found..
puts @str2.slice("Ruby")
puts @str2.slice("Ruby1").nil?

puts "++++++++++++=split eg+++++++++++++++++++"
s1= "This is a sample STRING..
testing with split method"

puts s1.split("..")
puts s1.split("\n")
puts s1.split(" ")
puts s1.split(" ", 2).inspect   #["This", "is a sample STRING..\ntesting with split method"]  split into 2

puts "++++++++++++=sub(replace in vbs) eg+++++++++++++++++++"
=begin
 method "sub" replaces the search string with other string only once..
 if you want to replace at all occurances, then use gsub method..
syntax:
str.sub(pattern, replacement) [or]
str.sub(pattern) { |match| block }
=end

s1= "This is ruby sample string"
puts s1.sub("is", "IS")     #ThIS is ruby sample string
puts s1.sub("is", "iS")   #ThiS is ruby sample string

puts s1.gsub("is", "IS")  #ThIS IS ruby sample string
puts s1.sub!(/(.)(.)/, '\2\1')   # => hTis is ruby sample string

S1= "hELLO woRLD"
# Checking for prefixes and suffixes: Ruby 1.9 and later
puts S1.start_with? "hE" # => true.  Note singular "start" not "starts"
puts S1.end_with? "bells"  # => false

puts "++++++++++++++++++case comparison+++++++++++++++"
# Case insensitive comparison. (ASCII text only)
# casecmp works like <=> and returns -1 for less, 0 for equal, +1 for greater
puts "world".casecmp("WORLD")  # => 0
puts "a".casecmp("B")          # => -1 (<=> returns 1 in this case)
puts "b".casecmp("a")

puts "+++++++++++++++Reverse examples++++++++++++++++++"
S1= "Helloo!"
puts S1.reverse
puts S1.chomp("o")         # => "hell": remove "o" from end


# Left-justify, right-justify, or center a string in a field n-characters wide.
# There are no mutator versions of these methods. See also printf method.
s = "x"
puts s.ljust(3)          # => "x  "
puts s.rjust(3)          # => "  x"
puts s.center(3)         # => " x "
puts s.center(5, '-')    # => "--x--": padding other than space are allowed
puts s.center(7, '-=')   # => "-=-x-=-": multicharacter padding allowed

Hashes in Ruby:

hash= Hash.new


puts hash[0].nil?     #returns true..

h2= Hash.new("default Value")

puts h2["key1"]  #returns default value..

h3= Hash.new
h3={'k1'=>'val1', 'k2'=> 'v2'}
puts h3.size
puts h3.inspect
puts h3.keys.inspect
puts h3['k2']


h4= Hash['a'=> 'apple', "b"=> 'bat']
puts h4


h5= Hash.new("Default")
arr1= [1,2,3,4]
arr2=['x','y','z','p']
for i in 0..arr1.size
h5[arr1[i]]=arr2[i]
end

puts '+++++++++++Using conditions+++++++++++++++++++'
puts h5.inspect
puts h5[4] unless h5[4].nil?
puts h5[4] if ! h5[4].nil?
puts h5[4] if not h5[4].nil?

h= Hash.new
h[1]='a'
puts h.inspect


For Hash related methods, refer: http://www.tutorialspoint.com/ruby/ruby_hashes.htm

Modules and Mixins

Modules and Mixins
In addition to classes, Ruby also has modules. A module is like a class, but it cannot be instantiated like a class. A class can include a module so that when the class is instantiated, it gets the included module’s methods and so forth. (The include method comes from the Module class: http://www.
ruby-doc.org/core/classes/Module.html.) The methods from an included module become instance methods in the class that includes the module. This is called mixing in, and a module is referred to as a mixin. You can include more than one module (which is similar to multiple inheritance), but
you can only inherit from one class (single inheritance).

Because identifiers are overridden by the last definition of the identifier (e.g., for methods or constants), this scheme avoids name collision. A module is a form of a namespace in Ruby.
A namespace is a set of names—such as method names—that have a scope or context. A Ruby class can also be considered a namespace.

A Ruby module associates a single name with a set of method and constant names. The module name can be used in classes or in other modules. Generally, the scope or context of such a namespace is the class or module where the namespace (module name) is included.

A module name must be a constant; that is, it must start with an uppercase letter. A module can contain methods, constants, other modules, and even classes. It can inherit from another module, but it may not inherit from a class. As a class may include a module, it may also include modules that have inherited other modules. Here’s an example:


module Dice
# virtual roll of a pair of dice
  def roll
       r_1 = rand(6); r_2 = rand(6)
       r1 = r_1>0?r_1:1; r2 = r_2>0?r_2:6
       total = r1+r2
       printf( "You rolled %d and %d (%d).\n", r1, r2, total )
     total
  end
end

class Game
    include Dice
end

g = Game.new
g.roll

If the module Dice and the class Game were in separate files, just require the file containing the module before including the module. The file containing the Dice module might look like this:

module Dice
   # virtual roll of a pair of dice
   def roll
     r_1 = rand(6); r_2 = rand(6)
     r1 = r_1>0?r_1:1; r2 = r_2>0?r_2:6
     total = r1+r2
     printf( "You rolled %d and %d (%d).\n", r1, r2, total )
     total
   end
end

And the file containing the Game class might look like this:

#!/usr/bin/env ruby
require 'dice'
class Game
   include Dice
end
g = Game.new
g.roll


Blocks in Ruby

Blocks

A block in Ruby is more than just a code block or group of statements. A Ruby block is always invoked in conjunction with a method, as you will see. In fact, blocks are closures, sometimes referred to as nameless functions. They are like a method within another method that refers to or shares variables with the enclosing or outer method. In Ruby, the closure or block is wrapped by braces ({}) or by do/end, and depends on the associated method (such as each) to work.

Here is an example call to a block on the method each from
Array:
pacific = [ "Washington", "Oregon", "California" ]
pacific.each do |element|
      puts element
end

The name in the bars (|element|) can be any name you want. The block uses it as a local variable to keep track of every element in the array, and later uses it to do something with the element. You can replace do/end with a pair of braces, as is most commonly done. The braces actually have a higher precedence

than do/end:
pacific.each { |e| puts e }

If you use a variable name that already exists in the containing scope, the block assigns that variable each successive value, which may or may not be what you  want. It does not generate a local variable to the block with that name, as some might expect. Thus, you get this behavior:

j = 7
(1..4).to_a.each { | j | } # j now equals 4

Just Arrays in Ruby

arr1= Array.new(10)
str1= "vicky ruby python qtp"
arr2= str1.split(" ")
puts arr2.inspect

puts arr1.size
puts arr2[0]

puts arr2.size
puts arr2[3]
arr1[0]="Testing"

puts arr1[0]

for i in (1..5)
  arr1[i-1]="value: "+ i.to_s
end
puts arr1.inspect

for ele in arr2
  puts ele.capitalize
end


# "+++++++++++++++++Array Declaration 2+++++++++++++++++++++++++++++++"
arr3= Array[5,8,6,7,9,3,4]
puts arr3.inspect
puts "Array arr3 size: #{arr3.length}"
puts arr3.sort.inspect    #[3, 4, 5, 6, 7, 8, 9]
puts arr3.sort().reverse.inspect  #[9, 8, 7, 6, 5, 4, 3]

arr4= ['x', 'z','o', 'p']
puts "is arr4 an array? - #{arr4.is_a?(Array)}"
puts "The class of arr4: #{arr4.class}"

puts "Join the array by '/' = #{arr4.join("/")}"  # it returns a string ..

dig=Array(1..9)
puts dig.inspect
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

puts dig[1, 2].inspect
puts dig[-1]
puts dig[1..5].inspect    #arr[range]

ar= [1,2,3,4]
puts ar.inspect
ar.clear    #when cleared, the will be cleared..
puts ar.size
puts ar.class
ar=[]
puts ar.size
puts ar.empty?


arr1= ['welcome', 'to', 'ruby']
for each in arr1
  puts each
  if each.casecmp("TO")
    puts "casecmp working.. ignores the case"
  end
  if each.eql?("tO")
    puts "eql? working.. ignores the case"
  else
    puts "eql? method doesn't ignore the case.."
  end

  if each.include?("by")
    puts "include working.. It's case insensitive."
  end
end


#Output:


["vicky", "ruby", "python", "qtp"]
10
vicky
4
qtp
Testing
["value: 1", "value: 2", "value: 3", "value: 4", "value: 5", nil, nil, nil, nil, nil]
Vicky
Ruby
Python
Qtp
[5, 8, 6, 7, 9, 3, 4]
Array arr3 size: 7
[3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3]
is arr4 an array? - true
The class of arr4: Array
Join the array by '/' = String
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3]
9
[2, 3, 4, 5, 6]
[1, 2, 3, 4]
0
Array
0
true
welcome
casecmp working.. ignores the case
eql? method doesn't ignore the case..
to
casecmp working.. ignores the case
eql? method doesn't ignore the case..
ruby
casecmp working.. ignores the case
eql? method doesn't ignore the case..
include working.. It's case insensitive.

Process finished with exit code 0

Saturday, 8 November 2014

Blocks and method to find type of a variable in Ruby

# Blocks Example:
arr=['x',1, 20.2, true, [1,2,3], false, 1..2, 1...3 ]
arr.each do |element|
  print element
  print " - is of: "
  puts (element).class
end

str1= "Hello"
ival= 1
fValue= 1.2
blnTrueVal= true
blnFalseVal=false
arr=[1,2,3,5]
rang= 1..3

puts "+++++++++++++++++++++++++++++++++++++++++"
# If we know the type of variable, then we can use the below to validate..
# to find the type of a variable object in Ruby:
puts str1.is_a?(String)  #Returns true if s is of type array variable
puts  ival.is_a?(Fixnum)
puts fValue.is_a?(Float)
puts blnTrueVal.is_a?(TrueClass)
puts blnFalseVal.is_a?(FalseClass)
puts arr.is_a?(Array)
puts  rang.is_a?(Range)

puts "+++++++++++++++++++++++++++++++++++++++++"
# to find out the type of variable's class: use below:
puts str1.class
puts ival.class
puts fValue.class
puts blnFalseVal.class
puts blnTrueVal.class
puts arr.class
puts rang.class



Output: x - is of: String
1 - is of: Fixnum
20.2 - is of: Float
true - is of: TrueClass
[1, 2, 3] - is of: Array
false - is of: FalseClass
1..2 - is of: Range
1...3 - is of: Range
+++++++++++++++++++++++++++++++++++++++++
true
true
true
true
true
true
true
+++++++++++++++++++++++++++++++++++++++++
String
Fixnum
Float
FalseClass
TrueClass
Array
Range

Accessing instance variable in ruby outside a class

class Basics
  @var="instance variable 1"
  @var1=0
  def initialize()
    @var1=1
  end
  def showMe()
    @var="instance variable is initialized here.."
  end
end

obj1= Basics.new
puts 'accessing instance variable b4 initializing it..'
puts "is nil ?"+ obj1.instance_variable_get(:@var).nil?.to_s
c= obj1.showMe()
puts "is instance var initialized: " + obj1.instance_variable_get(:@var).to_s
puts 'accessing instance variable: ' + obj1.instance_variable_get(:@var1).to_s

# You should not make this the default way you access instance variables as it violates encapsulation
# A better way is to define an accessor:
puts "+++++++++++++++++++++++++++++++++++++++++++"
class Hello
  @var1
  @var2=''
 def method1
   @hello = "venu"
   @var1="val1"
   @var2="val2"
 end
 attr_reader :hello
 attr_reader :var2
end

h = Hello.new
puts "check for @hello value b4 initialization.."
p h.hello #nil
p h.method1         #def/method return last evaluated value
p h.hello #"venu"   #accessing instance variable better way
puts h.var2         #accessing instance variable better way


Output:
accessing instance variable b4 initializing it..
is nil ?true
is instance var initialized: instance variable is initialized here..
accessing instance variable: 1
+++++++++++++++++++++++++++++++++++++++++++
check for @hello value b4 initialization..
nil
"val2"
"venu"
val2
++++++++++++++++++++++++++++++++++++++++=

http://stackoverflow.com/questions/12122736/access-instance-variable-from-outside-the-class

Sunday, 7 September 2014

Module include in another file

script file 1: sample_test.rb

module Mod1
  PI=3.14
  var=20
  CONST=10
  def Mod1.circleArea(iRadius)
    PI*(iRadius**2)
  end

  def Mod1.circlePerimeter(iRadius)
    2*PI*iRadius
  end

  def Mod1.requireTest()
    puts "This is to check whether methods gets executed when a module file is loaded with require or require_relative statement.."
  end
end


Script File 2: module_include.rb

require_relative 'pack/sample_test'
#sample_test.rb file is saved in pack folder..

class ModClass
 # include ModuleTest
  arr=[10,20,30]
  puts "Accessing PI from external file: #{Mod1::PI}"
  arr.each do |ele|
    puts "ar is: #{ele}"
    ar=Mod1.circleArea(ele)
    puts "Area of circle having radius= #{ele} is: #{ar}"
    pr=Mod1.circlePerimeter(ele)
    puts "Perimeter of circle having radius= #{ele} is: #{pr}"
  end
end

cls= ModClass.new

Nested Modules in Ruby

module Dojo
  A = 4
  module Kata
    B = 8
    module Roulette
      class ScopeIn
        def push
          var1=15
        end
      end
    end
  end
end

A = 16
B = 23
C = 42

puts "Local Variable- A : #{A}"
puts "Dojo::A - #{Dojo::A}"

puts "B - #{B}"
puts "Dojo::Kata::B - #{Dojo::Kata::B}"

puts

puts "C - #{C}"
puts "Dojo::Kata::Roulette::ScopeIn.new.push - #{Dojo::Kata::Roulette::ScopeIn.new.push}"


Output:
Local Variable- A : 16
Dojo::A - 4
B - 23
Dojo::Kata::B - 8

C - 42
Dojo::Kata::Roulette::ScopeIn.new.push - 15

Loops in Ruby

# #For loops
# while
# Until

str= "testing"
i= 1
while str=="testing"
  if i==5
    break
  end
  puts "Yes Testing"
  i= i+1
end

puts "While condition"
while i<10
  puts i.to_s
  i=i+1
end
puts "begin while condition similar to do..while in other programming languages"
#While condition begin..while
begin
  puts i.to_s
  i= i-1
end while i>=5

puts "until condition"

puts "until condition eg.."
until i>10
  puts "iterate loop as long as condition remain false..= "+ i.to_s
  i= i+1
end


puts "begin .. until loop similar to the do..until in vbscript"

x=15
begin
  puts "i value if i>10:.. "+ x.to_s   #condition is true.. so until won't be executed but this loop will be executed atleast once
  x= x-1
end until x>10

puts "For loop egs:"

for i in (1..5)
  puts i.to_s
end

for i in (2..10).step(2)
  puts "increment i by 2 = #{i}"
end

puts "decrement for loop eg:"

for i in (7).downto(0)
  puts "for loop decrement: #{i}"
end

# error: step can't be negative (ArgumentError)
# for i in (10..1).step(-2)
#   puts "decrement i by 2 = #{i}"
# end

puts "each do loop egs: "
(1..5).each do |x|
  puts "each do loop value= #{x}"
end

# ++++++++++++++++++++++++++++++++++++++++
(2..10).step do |i|
  puts "i in step do #{i}"
end

(1..12).step(3) do |i|
  puts "i in step do #{i}"
end

1.step(15, 2) do |x|
  puts "increment by 2 where x is: #{x}"
end

15.step(1, -3){
  |x| puts ".step decrement by 3 where x is= #{x}"
}

i=6
i.downto(2) do |i|
  puts "downto do loop where i is : #{i}"
end

('a'..'e').each do |al|
  puts al
end

(1..5).step(2).each do |x|        #when the loop increments, we give range first
  puts "each do loop value= #{x}"
end

10.step(1, -2) do |x|
  print x
end

# ++++++++++++++++++++++++++++++++++++++++



Output:

Yes Testing
Yes Testing
Yes Testing
Yes Testing
While condition
5
6
7
8
9
begin while condition similar to do..while in other programming languages
10
9
8
7
6
5
until condition
until condition eg..
iterate loop as long as condition remain false..= 4
iterate loop as long as condition remain false..= 5
iterate loop as long as condition remain false..= 6
iterate loop as long as condition remain false..= 7
iterate loop as long as condition remain false..= 8
iterate loop as long as condition remain false..= 9
iterate loop as long as condition remain false..= 10
begin .. until loop similar to the do..until in vbscript
i value if i>10:.. 15
For loop egs:
1
2
3
4
5
increment i by 2 = 2
increment i by 2 = 4
increment i by 2 = 6
increment i by 2 = 8
increment i by 2 = 10
decrement for loop eg:
for loop decrement: 7
for loop decrement: 6
for loop decrement: 5
for loop decrement: 4
for loop decrement: 3
for loop decrement: 2
for loop decrement: 1
for loop decrement: 0
each do loop egs:
each do loop value= 1
each do loop value= 2
each do loop value= 3
each do loop value= 4
each do loop value= 5
i in step do 2
i in step do 3
i in step do 4
i in step do 5
i in step do 6
i in step do 7
i in step do 8
i in step do 9
i in step do 10
i in step do 1
i in step do 4
i in step do 7
i in step do 10
increment by 2 where x is: 1
increment by 2 where x is: 3
increment by 2 where x is: 5
increment by 2 where x is: 7
increment by 2 where x is: 9
increment by 2 where x is: 11
increment by 2 where x is: 13
increment by 2 where x is: 15
.step decrement by 3 where x is= 15
.step decrement by 3 where x is= 12
.step decrement by 3 where x is= 9
.step decrement by 3 where x is= 6
.step decrement by 3 where x is= 3
downto do loop where i is : 6
downto do loop where i is : 5
downto do loop where i is : 4
downto do loop where i is : 3
downto do loop where i is : 2




Arrays in Ruby

a= Array.new(10)
puts a.size
puts a[0].nil?
puts "is array nil: #{a.nil?}"
puts a[0]="testing"
puts a[0] if not(a[0].nil?)   #we can even say: !(a[0].nil?) .. gives the same result..

x= true
y= false
if x and y
  puts "True"
else
  puts "False"
end


b= Array.new
puts "is Array b nil? : #{b.nil?}"
puts "b array size: #{b.size}"   #size is zero here..

c=Array["vicky","ruby"]
puts "c array size is: #{c.size}"   # size is 1 here.. it has one element..

d= Array.[]("RUBY", "EASY", c)
puts "Array 'd' size is: "+ d.length.to_s


e= Array(21..25)
puts "Array e is : #{e}"


f= Array[1, 2, 5, 3, 6,9]
puts "sort array f: #{f.sort}"
p= f.clear
puts "post array clear, array size is: #{f.size}"
puts "join array: #{d.join("/")}"

puts "reverse array: #{d.reverse}"

x=Array[1,2,3]
puts x.size + x[1]

y=[1,2,3,4,5,6,7]
puts y[2]


Output:
10
true
is array nil: false
testing
testing
False
is Array b nil? : false
b array size: 0
c array size is: 2
Array 'd' size is: 3
Array e is : [21, 22, 23, 24, 25]
sort array f: [1, 2, 3, 5, 6, 9]
post array clear, array size is: 0
join array: RUBY/EASY/vicky/ruby
reverse array: [["vicky", "ruby"], "EASY", "RUBY"]
5
3