http://www.ietf.org/rfc/rfc2616.txt
Tuesday, 25 November 2014
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
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
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
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
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
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
@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
Subscribe to:
Posts (Atom)