Pages

Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Sunday, February 11, 2018

Ruby’s Hash Vs ActiveSupport’s HashWithIndifferentAccess


The Hash class in Ruby’s core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :some_value) cannot be retrieved using the equivalent String (e.g. ‘some_value’). 
On the other hand, class HashWithIndifferentAccess is inherited from ruby "Hash" & a special behavior is added in it. HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:

h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"

Monday, July 13, 2015

Ruby Inheritance, Encapsulation and Polymorphism

Inheritance
Inheritance is a relation between two classes. A child class inherits all the features of its parent class. Methods from the parent can be overridden in the child and new logic can be added.
Usually, inheritance is used to specialize a class. See the following example :
class Document
  def initialize; end

  # logic to deal with any document

  def print
    # logic to print any kind of document
  end
end
class XmlDocument < Document
  # logic to deal with any document

  def print
    # logic to print a xml document
  end
end
A class can only inherit from one class as opposed to c++ where multi-inheritance can be done (not always for the better).

Thursday, May 1, 2014

Ruby remove duplicate entries in array of hashes but based on more than one value

Suppose you have the following array of hashes:

new_tracks = [{:name=>"Yes, Yes, Yes", :artist=>"Some Dude", :composer=> 'First Dude', :duration=>"3:21"},
 {:name=>"Chick on the Side", :artist=>"Another Dude", :duration=>"3:20"},
 {:name=>"Luv Is", :duration=>"3:13"},
 {:name=>"Yes, Yes, Yes", :artist=>"Some Dude", :composer=> 'First Dude', :duration=>"2"},
 {:name=>"Chick on the Side", :artist=>"Another Dude"}]

uniq accepts a block. If a block is given, it will use the return value of the block for comparison.
You can join the attributes you want into a string and return that string.

new_tracks.uniq { |track| [track[:name], track[:artist]].join(":") }

The resultant of above code will be an array of hashes unique on the basis of name and artist attributes.

Thursday, January 9, 2014

Ruby Way - Swap two variables

In Ruby, you can easily swap values of two variables without the need for a temporary third variable:
x,y = y,x
This is called ‘Parallel Assignment’.
Can’t believe it? I had to test it myself, too:
$ irb
>> x = 5
=> 5
>> y = 10
=> 10
>> x,y = y,x
=> [10, 5]
>> x
=> 10
>> y
=> 5

3 ways to invoke a method in Ruby

You can use following methods to invoke any method in ruby -

object = Object.new

1. The dot operator (or period operator)
puts object.object_id
 #=> 282660

2. The Object#send method
puts object.send(:object_id)
 #=> 282660

3. The method(:foo).call
puts object.method(:object_id).call
 #=> 282660

Wednesday, January 8, 2014

Ruby - A Duck Typed Language

Duck Typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. The name of the concept refers to the duck test, attributed to James Whitcomb Riley , which may be phrased as follows:
When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.
In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. For example, in a non-duck-typed language, one can create a function that takes an object of type Duck and calls that object's walk and quack methods. In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error. If the object does have the methods, then they are executed no matter the type of the object, evoking the quotation and hence the name of this form of typing.

Ruby - Format dates with suffix, like “Sun Oct 5th”

Use the ordinalize method from 'active_support'.
>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"
Note, if you are using IRB with Ruby 2.0, you must first run:
require 'active_support/core_ext/integer/inflections'

Friday, January 3, 2014

nil vs empty vs blank in Ruby on Rails

.nil?
.nil? can be used on any object and is true if the object is nil.
.empty?
.empty? can be used on strings, arrays and hashes and returns true if:
  • String length == 0
  • Array length == 0
  • Hash length == 0
Running .empty? on something that is nil will throw a NoMethodError.
.blank?
That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.
nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
.blank? also evaluates true on strings which are non-empty but contain only whitespace:
"  ".blank? == true
"  ".empty? == false
Rails also provides .present?, which returns the negation of .blank?.

Monday, December 30, 2013

Blocks in Ruby

Ruby has a concept of Block.
  • A block consists of chunks of code.
  • You assign a name to a block.
  • The code in the block is always enclosed within braces ({}).
  • A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block.
  • You invoke a block by using the yield statement.

Syntax:

block_name{
   statement1
   statement2
   ..........
}
Here, you will learn to invoke a block by using a simple yield statement. You will also learn to use ayield statement with parameters for invoking a block. You will check the sample code with both types ofyield statements.

Monday, December 23, 2013

14 Bare Minimum Security Checks Before Releasing a Rails App

When you upload your latest app to a production Web server and open it up to the world, you're really throwing your app to the elements - good and bad. If you don't pay any attention to security whatsoever, you're likely to fall foul of some cracker's nefarious scheme and your users will be complaining when something doesn't work or they're being spammed by geriatric Nigerian clowns with pots of gold to share. But what to do?
Luckily, help is at hand in the shape of the official Ruby on Rails Security Guide, but Irish Rails developer Matthew Hutchinson has trawled through that guide as well as several illuminating blog posts relating to Rails security, and put together a 14 step checklist of "bare minimum" security checks to do before releasing your Rails app.
In summary:
  1. Don't trust logged in users. (Authentication is one thing, authorization to perform certain tasks is another.)
  2. Beware of mass assignments. (Use attr_accessible in your models!)

Monday, May 20, 2013

The difference between require, load, Include and Extend

Here are the differences between Include, Load,Require and Extend methods in Ruby : 

--> Include: 

When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module. 

The following assumes that the module Log and class TestClass are defined in the same .rb file. If they were in separate files, then ‘load’ or ‘require’ must be used to let the class know about the module you’ve defined. 


module Log 
def class_type 
"This class is of type: #{self.class}" 
end 
end 

class TestClass 
include Log 
# ... 
end 

tc = TestClass.new.class_type 

The above will print “This class is of type: TestClass”