Ruby Interesting Facts: Things might not be falsy as you consider

It might amaze us but there are some facts about ruby we need to know to write bug free codes.

# empty_string "" is treated as "true"
empty_string = "" 
if empty_string 
  puts "Empty string (\"\") is considered as TRUE" 
end 
# Output Empty string (\"\") is considered as TRUE

 

0 is treated as “true

zero = 0
if zero
	puts "Zero is considered as TRUE"
end
 # Output
Zero is considered as TRUE

Empty Array [ ] is treated as “true

empty_array = []
if empty_array
	puts "Empty array ([]) is considered as TRUE"
end

# Output
Empty array ([]) is considered as TRUE

however, nil is considered ‘false

nothing = nil
unless nothing
	puts "nil is considered as FALSE"
end
 
# Output
nil is considered as FALSE

 

2.2.1 :041 > 0.present?
 => true 
2.2.1 :042 > [].present?
 => false 
2.2.1 :043 > ''.present?
 => false 
2.2.1 :044 > [nil].present?
 => true

 

Interesting Features of Ruby OOP

Multiple variables can be initialized at once in ruby

class Box
   def initialize(w,h)
      @width, @height = w, h
   end
end

Multiple values can be returned from functions/methods in ruby

class Box
   	def initialize(w,h)
      @width, @height = w, h
   	end
	
	def get_dimensions
		return @width, @height
	end
end
new_box = Box.new 12,13
pry(main)> width, height = new_box.get_dimensions
=> [12, 13]

The accessor & setter methods:

class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # accessor methods
   def getWidth
      @width
   end
   def getHeight
      @height
   end

   # setter methods
   def setWidth=(value)
      @width = value
   end
   def setHeight=(value)
      @height = value
   end
end

# create an object
box = Box.new(10, 20)

# use setter methods
box.setWidth = 30
box.setHeight = 50

# use accessor methods
x = box.getWidth()
y = box.getHeight()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"
Width of the box is : 30
Height of the box is : 50

The class methods & variables:

The class variables is a variable which is shared between all instances of a class. In other words, there is one instance of the variable and it is accessed by object instances. Class variables are prefixed with two @ characters (@@). A class variable must be initialized within the class definition as shown below.

A class method is defined using def self.methodname() which ends with end delimiter and would be called using class name as classname.methodname as shown in the following example:

#!/usr/bin/ruby -w

class Box
   # Initialize our class variables
   @@count = 0
   def initialize(w,h)
      # assign instance variables
      @width, @height = w, h

      @@count += 1
   end

   def self.printCount()
      puts "Box count is : #@@count"
   end
end

# create two object
box1 = Box.new(10, 20)
box2 = Box.new(30, 100)

# call class method to print box count
Box.printCount()
Box count is : 2

Freezing Objects:

Sometimes, we want to prevent an object from being changed. The freeze method in Object allows us to do this, effectively turning an object into a constant. Any object can be frozen by invokingObject.freeze. A frozen object may not be modified: you can’t change its instance variables.

You can check if a given object is already frozen or not usingObject.frozen? method, which returns true in case object is frozen otherwise a false value is return. Following example clears the concept:

#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # accessor methods
   def getWidth
      @width
   end
   def getHeight
      @height
   end

   # setter methods
   def setWidth=(value)
      @width = value
   end
   def setHeight=(value)
      @height = value
   end
end

# create an object
box = Box.new(10, 20)

# let us freez this object
box.freeze
if( box.frozen? )
   puts "Box object is frozen object"
else
   puts "Box object is normal object"
end

# now try using setter methods
box.setWidth = 30
box.setHeight = 50

# use accessor methods
x = box.getWidth()
y = box.getHeight()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"

When the above code is executed, it produces the following result:

Box object is frozen object test.rb:20:in `setWidth=': can't modify frozen object (TypeError) from test.rb:39

Class Constants:

You can define a constant inside a class by assigning a direct numeric or string value to a variable which is defined without using either @ or @@. By convention we keep constant names in upper case.

Once a constant is defined, you can not change its value but you can access a constant directly inside a class much like a variable but if you want to access a constant outside of the class then you would have to use classname::constant as shown in the below example.

#!/usr/bin/ruby -w

# define a class
class Box
   BOX_COMPANY = "TATA Inc"
   BOXWEIGHT = 10
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # instance method
   def getArea
      @width * @height
   end
end

# create an object
box = Box.new(10, 20)

# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
puts Box::BOX_COMPANY
puts "Box weight is: #{Box::BOXWEIGHT}"

Create object using allocate:

There may be a situation when you want to create an object without calling its constructor initialize ie. using new method, in such case you can call allocate which will create an uninitialized object for you as in the following example:

#!/usr/bin/ruby -w

# define a class
class Box
   attr_accessor :width, :height

   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # instance method
   def getArea
      @width * @height
   end
end

# create an object using new
box1 = Box.new(10, 20)

# create another object using allocate
box2 = Box.allocate

# call instance method using box1
a = box1.getArea()
puts "Area of the box is : #{a}"

# call instance method using box2
a = box2.getArea()
puts "Area of the box is : #{a}"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s