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

No comments:

Post a Comment