Skip to main content

Posts

Showing posts from May, 2015

List of Common mistakes in Ruby

Always use spaces around operators, after commas, colons and semicolons, around { and before }.  White space  might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code. Also it makes the design more readable and code much cleaner. product = 1 * 2 array = [ 1 , 2 , 3 , 4 , 5 ] array.map { |a| a + 2 } There should be no spaces after (, [ or before ], ) these brackets. [ 'ankur' , 'vyas' ] sum(a, b) Also don't use spaces in while providing the range. Use 5 .. 9 over 5 .. 9 Use 'a' .. 'z' over 'a' .. 'z' When using switch case statements use the following indentation. case when input = '+' puts 'The operation is addition' when '-' puts 'The operation is subtraction' when '*' puts 'The operation is multiplication' else puts 'The operat

Scope and Access modifiers in Ruby

Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers set the visibility of methods and member fields. Ruby has three access modifiers: public , protected and private . In Ruby, all data members are private. Access modifiers can be used only on methods. Ruby methods are public, unless we say otherwise. The scope of the methods is until another scope comes i.e. when we write private all the methods below it are private until any other scope (i.e. protected or public). NOTE: Ruby does not apply any access control over instance and class variables. Public Methods: Public methods can be called by anyone. Methods are public by default except for initialize, which is always private. Private Methods: Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members. Protected Methods: A protected met

Ruby Mixins

What’s a Mixin? A mixin can basically be thought of as a set of code that can be added to one or more classes to add additional capabilities without using inheritance. In Ruby, a mixin is code wrapped up in a module that a class can include or extend. In fact, a single class can have many mixins. When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance. Ruby does not support multiple inheritance directly but Ruby Modules have another wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin . module A def a1 end def a2 end end module B def b1 end def b2 end end class Sample include A include B def s1 end end samp= Sample .new samp.a1 # From module A samp.a2 # From module A samp.b1 # From module B samp.b2 # From module B samp.s1 # Instance method In the example above, the object of the