Many times we come across such situations where we need to group records, like when we want to display grouped messages, email, alerts .etc based on date or time. Here is the simple code which provides a significant use of group_by method. Controller Part class MessagesController < ApplicationController def index @message = Message .all #Retrives all messages and divides into two groups todays messages and other messages @grouped_messages = @message .group_by{ |t| t.created_at.to_date == DateTime .now.to_date } if @grouped_messages [ false ].present? #Create month wise groups of messages @month_wise_sorted_alerts = @grouped_messages [ false ].group_by{ |t| t.created_at.month} end end end @message .group_by{ |t| t.created_at.to_date == DateTime .now.to_date } The above line return us the messages in Ordered Hash with two keys true and false on which the messages which are of today's date will be valu
Definition : " Poly " stands for " many " and " morph " stands for " forms ". Generally, polymorphism means one name different uses . Technically, it means being able to send the same message to different objects and get different result. Polymorphism through Inheritance We can achieve polymorphism through inheritance . For example class GenericParser def parse raise NotImplementedError , 'You must implement the parse method' end end class JsonParser < GenericParser def parse puts 'An instance of the JsonParser class received the parse message' end end class XmlParser < GenericParser def parse puts 'An instance of the XmlParser class received the parse message' end end Here the GenericParser is the base class. Class JsonParser and XmlParser are inherited from the GenericParser. Now suppose we run the below code. puts 'Using the XmlParser' parser