Wednesday 22 June 2016

Ruby Load Path and Auto Loading in Rails - Other small concepts





Hi Readers,

This is the last post for Ruby beginners. Today we are going to learn some small concepts and Ruby load paths and auto loading in Rails

define_method:

class Array 
  {:second => 1, :third => 2}.each do |method,element| 
    define_method(method) do 
      self[element] 
    end 
  end 
end 
 
array = %w(A B C) 
puts array.first # => A 
puts array.second # => B 
puts array.third # => C  

Object Space:

    ObjectSpace.each_object(Numeric) { |n| puts n }   

Class Reflection:

    # Using Class#superclass 
    klass = Fixnum 
    begin 
      print klass 
      klass = klass.superclass 
      print " < " if klass 
    end while klass 
    # => Fixnum < Integer < Numeric < Object 
     
    # Using Class#ancestors 
    Fixnum.ancestors 
    # => Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel 
     
    # Inspecting methods and variables 
    Fixnum.public_instance_methods(false) 
    Fixnum.class_variables 
    Fixnum.constants 
    1.instance_variables

System Hooks: Class#inherited

    class A 
      @@subclasses = {}   
      # Invoked when a new class is created that extends this class 
      def self.inherited(child) 
        puts "inherited" 
        @@subclasses[self] ||= [] 
        @@subclasses[self] << child 
      end 
       
      def self.subclasses 
        @@subclasses[self] 
      end 
    end 
     
    class B < A 
    end 
     
    puts A.subclasses   

Ruby Load Path and Auto Loading in Rails:

  • The Ruby load path is stored in $: and is used when you require code
  • Models, views, controllers, and helpers under the app dir are loaded automatically
  • Classes under lib are also loaded automatically
  • You can add load paths in config/environment.rb
  • Class and module names must correspond to the file path where they are defined for auto loading to work


Tuesday 14 June 2016

const_missing – for Auto Loading Classes, eval and binding

Hi Readers,

Today we are going to learn that if any class is not defined, even though you are trying to create object for that non existing class, then ruby raises an exception called "constant_missing".

const_missing – for Auto Loading Classes:

    def Object.const_missing(name)  
      @looked_for ||= {}  
      str_name = name.to_s  
      raise "Class not found: #{name}" if @looked_for[str_name]  
      @looked_for[str_name] = 1  
      file = str_name.downcase  
      require file  
      klass = const_get(name)  
      return klass if klass  
      raise "Class not found: #{name}"  
    end  

eval and binding:

def evaluate_code(code, binding) 
  a = 2 
  eval code, binding 
end 
 
a = 1 
evaluate_code("puts a", binding) # => 1

instance_eval:

    require 'person_class'  
    andreas = Person.new("Andreas")  
    puts andreas.instance_eval { @name } # => Andreas  

class_eval and module_eval:

    class Person 
      def self.add_method(method) 
        class_eval %Q{ 
          def #{method} 
            puts "method #{method} invoked" 
          end 
        } 
      end     
     
      add_method(:say_hi) 
    end 
     
    Person.new.say_hi   


Thank for reading it, hope you will practice and get some idea.




Monday 13 June 2016

method_missing: A VCR and Using the VCR


Hi Readers,

Today we are going to take an example class VCR and verify the method_missing concept.

method_missing: A VCR

    class VCR 
      def initialize 
        @messages = [] 
      end 
     
      def method_missing(method, *args, &block) 
        @messages << [method, args, block] 
      end 
     
      def play_back_to(obj) 
        @messages.each do |method, args, block| 
          obj.send(method, *args, &block) 
        end 
      end 
    end

Using the VCR:

    require 'vcr' 
     
    vcr = VCR.new 
    vcr.gsub! /Ruby/, "Crazy" 
    vcr.upcase! 
    object = "I Go Ruby" 
    vcr.play_back_to(object) 
    puts object  


Just practice this example , i will get back to you with new concept.

Thanks for reading, subscribe this blog to get more updates.

Friday 10 June 2016

Open Class Definitions and Method Aliasing


Hi readers,

In this post we are going to learn how to open existing class defination and alias the method which is exist already in the class.

Open Class Definitions and Method Aliasing:

    class Peter 
      def say_hi 
        puts "Hi" 
      end 
    end 
     
    class Peter 
      alias_method :say_hi_orig, :say_hi 
      def say_hi 
        puts "Before say hi" 
        say_hi_orig 
        puts "After say hi" 
      end 
    end 
     
    Peter.new.say_hi  

Core Classes are Also Open:

 class Integer
  def even?
    (self % 2) == 0
  end
end
 
p (1..10).select { |n| n.even? } # => [2, 4, 6, 8, 10] 

Hope you understand the concept and you will practice this.
Thanks for reading this, if like share this.

Wednesday 8 June 2016

RDoc and Option Parsing - Ruby on the Command Line

Hi Readers,

Today we are going to learn RDoc and Option Parsing, means ruby documentation and their options. In this we are also using ruby in command line.

RDoc and Option Parsing:

#!/usr/bin/env ruby 
# == Synopsis 
# This script takes photographs living locally on my desktop or laptop 
# and publishes them to my homepage at http://marklunds.com. 

# == Usage 

# Copy config file publish-photos.yml.template to publish-photos.yml and edit as appropriate. 
# ruby publish-photos [ -h | --help ] <photo_dir1> ... <photo_dirN> 
 
# Load the Rails environment 
require File.dirname(__FILE__) + '/../config/environment' 
require 'optparse' 
require 'rdoc/usage' 
 
opts = OptionParser.new 
opts.on("-h", "--help") { RDoc::usage('usage') } 
opts.on("-q", "--quiet") { Log::Logger.verbose = false } 
opts.parse!(ARGV) rescue RDoc::usage('usage')   

Ruby on the Command Line:

# Query and replace 
ruby -pi.bak -e "gsub(/Perl/, 'Ruby')" *.txt 
 
# Grep 
ruby -n -e "print if /Ruby/" *.txt 
ruby -e "puts ARGF.grep(/Ruby/)" *.txt

Hope you will get this concepts.
Share this page. Place comment on it.

Tuesday 7 June 2016

Dup method, Regular expressions and invoking external programs

The dup Method and Method Arguments:

    # Methods that change their receiver end with an exclamation mark by convention. 
    # If you need to invoke an exclamation mark method on a method argument and you want 
    # to avoid the object from being changed, you can duplicate the object first 
    # with the Object#dup method. Core classes such as String, Hash, and Array all have 
    # meaningful implementations of the dup method. Here is an example from Rails: 
     
    class ActiveRecord::Base 
      def attributes=(new_attributes) 
        return if new_attributes.nil? 
        attributes = new_attributes.dup # duplicate argument to avoid changing it 
        attributes.stringify_keys! # modify the duplicated object 
        # ... method continues here 
      end 
    end   

Regular Expressions:

    "Ruby" =~ /^(ruby|python)$/i 
    "Go\nRuby" =~ /Go\s+(\w+)/m; $1 == "Ruby" 
    "I Go Ruby" =~ /go/i; $& == "Go"; $` == "I "; $' == " Ruby"
    pattern = "."; Regexp.new(Regexp.escape(pattern))
    "I Go Ruby"[/(go)/i, 1] == "Go"
    puts "I Go Ruby".gsub(%r{Ruby}, '\0 or I go bananas') 
    "I Go Ruby".gsub(/ruby/i) { |lang| lang.upcase } 
    line = "I Go Ruby" 
    m, who, verb, what = *line.match(/^(\w+)\s+(\w+)\s+(\w+)$/) 
    # \s, \d, [0-9], \w - space, digit, and word character classes 
    # ?, *, +, {m, n}, {m,}, {m} - repetition   

Invoking External Programs:

    system("ls -l") 
    # $? is a predefined variable with the exit status 
    puts $?.exitstatus if !$?.success? 
    # The back ticks "`" return the output of the external program 
    standard_out = `ls -l`   


Hope you understand the concepts.

if like
   share
else
   comment
end

Thank You

Monday 6 June 2016

Case statements, Blocks and String operations

Hi Readers,

Today we are going to learn how to write case statements in Ruby. Know about ruby blocks and some string operations with examples.

Case:

    x = 11 
    case x 
    when 0 
    when 1, 2..5 
      puts "Second branch" 
    when 6..10 
      puts "Third branch" 
    when *[11, 12] 
      puts "Fourth branch" 
    when String: puts "Fifth branch" 
    when /\d+\.\d+/ 
      puts "Sixth branch" 
    when x.to_s.downcase == "peter" 
      puts "Seventh branch" 
    else 
      puts "Eight branch" 
    end   

Blocks - Usage examples:

    # Iteration 
    [1, 2, 3].each { |item| puts item } 
     
    # Resource Management 
    File.open("file.txt", "w") do |file| 
      file.puts "foobar" 
    end 
     
    # Callbacks 
    widget.on_button_press do 
      puts "Got button press" 
    end 
     
    # Convention: one-line blocks use {...} and multiline 
    # blocks use do...end  

Common String Operations:

    "  ".empty? == true 
    IO.read(__FILE__).each_with_index { |line, i| puts "#{i}: #{line}" } 
    "abc".scan(/./).each { |char| char.upcase } 
    "we split words".split.join(", ") 
    "    strip space   ".strip 
    sprintf("value of %s is %.2f", "PI", 3.1416) 
    "I Go Ruby"[2, 2] == "I Go Ruby"[2..3] # => "Go"   

Hope you will understand this concepts. Next we will meet with different concept.
Please practice these to get hands on experience.

Share if you like else comment.

Ruby Conditional statements and Iterators

Hi Readers,

In this we are going to learn conditions and Iterators in Ruby. Please follow the below concepts.

if, unless, and the ? Operator

message = if count > 10 
            "Try again" 
          elsif tries == 3 
            "You lose" 
          else 
            "Enter command" 
          end 
 
raise "Unauthorized" if !current_user.admin? 
raise "Unauthorized" unless current_user.admin? 
 
status = input > 10 ? "Number too big" : "ok"  

Iterators: while, until, for, break, and next

while count < 100 
  puts count 
  count += 1 
end 
 
payment.make_request while (payment.failure? and payment.tries < 3) 
 
for user in @users 
  next if user.admin? 
  if user.paid? 
    break 
  end 
end 
 
until count > 5 
  puts count 
  count += 1 
end   


Practice with different conditions,
Please share this to help others.

 


Ruby Range class, Structs and Exceptions

Hi readers,

In this post we are going to know about Range class, Structs in ruby and exceptions.

Range Class:

    # Two dots is inclusive, i.e. 1 to 5 
    (1..5).each { |x| puts x**2 }  
     
    # Three dots excludes the last item, i.e. 1 to 4 
    (1...5).each { |x| puts x } 
     
    (1..3).to_a == [1, 2, 3]  

Structs:

    Rating = Struct.new(:name, :ratings)  
    rating = Rating.new("Rails", [ 10, 10, 9.5, 10 ])  
     
    puts rating.name 
    puts rating.ratings  

Exceptions:

    begin  
      raise(ArgumentError, "No file_name provided") if !file_name 
      content = load_blog_data(file_name) 
      raise "Content is nil" if !content  
    rescue BlogDataNotFound  
      STDERR.puts "File #{file_name} not found"  
    rescue BlogDataConnectError 
      @connect_tries ||= 1 
      @connect_tries += 1 
      retry if @connect_tries < 3  
      STDERR.puts "Invalid blog data in #{file_name}"  
    rescue Exception => exc  
      STDERR.puts "Error loading #{file_name}: #{exc.message}" 
      raise 
    end  


Just can you practice above examples, then you will understand the concept, otherwise place comment on it.

Thank you share with your friends.

Ruby Symbols And More about Methods

Ruby Symbols:

# Symbols start with a colon 
:action.class == Symbol 
:action.to_s == "action" 
:action == "action".to_sym 
 
# There is only one instance of every symbol 
:action.equal?(:action) # => true 
'action'.equal?('action') # => false 
 
# Symbols are typically used as keys in hashes 
my_hash = {:controller => "home", :action => "index"} 

More about Methods:

  • Arbitrary number of arguments: def my_methods(*args)
  • Converting Array to arguments: my_method([a, b]*)
  • Dynamic method invocation: object.send(:method_name)
  • Duck typing: object.respond_to?(:method_name)
  • If the last argument is a Hash, the braces can be omitted: link_to("Home", :controller => "home")
 Hi readers,

hope you learn today post.

Leave comment or share.

Friday 3 June 2016

Arithmetic and Conversions, String, Array and Hash

Arithmetic and Conversions:

    2.class == Fixnum 
    Fixnum.superclass == Integer 
    Integer.superclass == Numeric 
     
    3.0.class == Float 
    Float.superclass == Numeric 
     
    2/3 == 0 
    2/3.0 # => 0.6666667 
    2 + 3.0 == 5.0 
    "2".to_i + "3.0".to_f == 5.0 
     
    10000000000.class == Bignum 
    Bignum.superclass == Integer 
     
    2 + "3" # => TypeError: String can't be coerced into Fixnum   

String Class:

    "ruby".upcase + " " + "rails".capitalize # => RUBY Rails 
     
    "time is: #{Time.now}\n second line" 
     
    'no interpolation "here" #{Time.now}' # => no interpolation "here" #{Time.now} 
     
    "I" << "Go" << "Ruby" # => IGoRuby 
     
    %Q{"C" and "Java"} # => "C" and "Java" 
     
    %q{single 'quoted'} # => single 'quoted' 
     
    <<-END 
        A here 
        document at #{Time.now} 
    END  

Array Class:

    a = ["Ruby", 99, 3.14] 
    a[1] == 99 
    a << "Rails" 
    ['C', 'Java', 'Ruby'] == %w{C Java Ruby} 
    [1, 2, 3].map { |x| x**2 }.join(", ") 
    [1, 2, 3].select { |x| x % 2 == 0 } 
    [1, 2, 3].reject { |x| x < 3 } 
    [1, 2, 3].inject { |sum, i| sum + i } 
     
    [1, [2, 3]].flatten! # => [1, 2, 3] 
     
    %w{C Java Ruby}.include?("C") # => true 
     
    fruits = ['apple', 'banana'] 
    fruits += ['apple'] unless fruits.include?('apple') 
    [1, 3, 5] & [1, 2, 3] # (intersection) => [1, 3] 
    [1, 3, 5] | [2, 4, 6] # (union) => [1, 3, 5, 2, 4, 6] 
    [1, 2, 3] - [2, 3] # (difference) => [1]   

Hash Class:

h = {:lang => 'Ruby', :framework => 'Rails'} 
h[:lang] == 'Ruby' 
h[:perl] == nil 
puts h.inspect 
env = {"USER" => "peter", "SHELL" => "/bin/bash"} 
env.each {|k, v| puts "#{k}=#{v}" }

Practice this i will get back to you with new concept.
Subscribe this blog for new updates.

Ruby Object, Constants and Introspection

Everything is an Object:

  • 2 + 2 is equivalent to 2+(2) and 2.send(:+, 2)
  • 2.hours.ago
  • 2.class # => Fixnum
  • 2.class.instance_methods – Object.instance_methods
  • “andreas”.capitalize

Constants:

  • Constants defined in a class/module are available within that class/module and outside the class with the scope operator ::
  • Constants defined outside any class/module can be accessed anywhere
  • Constants cannot be defined in methods

Introspection:

andreas = Person.new("Andreas") 
andreas.inspect # => #<Person:0x1cf34 @name="Andreas"> 
 
andreas.class # => Person 
andreas.class.superclass # => Object 
andreas.class.superclass.superclass # => nil 
 
andreas.class.ancestors.join(", ") # Person, Object, Kernel 
 
Person.instance_methods(false) # => say_hi 
Kernel.methods.sort.join("\n") # => All methods in Kernel module  

Hope you learn something to day.

Follow this blog By subscribing.

Thanks



Thursday 2 June 2016

Ruby Modules and Modules vs Classes

Hi Readers,

Modules:

    require 'person_class' 
    module HasAge 
      attr_accessor :age 
    end 
    class Person 
      include HasAge 
    end 
    peter = Person.new("Peter"); peter.age = 33; puts peter.age 
    module MyApp 
      class Person 
        attr_accessor :hometown 
        def initialize(hometown) 
          self.hometown = hometown 
        end 
      end 
    end 
    peter = MyApp::Person.new("Stockholm"); puts peter.hometown 

Modules vs Classes:

  • Modules model characteristics or properties of entities or things. Modules can’t be instantiated. Module names tend to be adjectives (Comparable, Enumerable etc.). A class can mix in several modules.
  • Classes model entities or things. Class names tend to be nouns. A class can only have one super class (Enumeration, Item etc.).

Hope you understand.

Thanks

 


Wednesday 1 June 2016

Ruby - Assignment concept


Hi Readers,

Today we are going learn assignment of a variable value in ruby.

Assignment:

  • a, b = b, a # swapping values
  • a = 1; b = 1
  • a = b = 1
  • a += 1 # a = a + 1
  • a, b = [1, 2]
  • a = b || c
  • a ||= b

Idiom: Assignment with Boolean Expression

    comment = Object.new 
    def comment.user 
      Object.new 
    end 
     
    # Overly verbose: 
    user_id = nil 
    if comment 
      if comment.user 
        user_id = comment.user.object_id 
      end 
    end 
     
    # Idiomatic: 
    user_id = comment && comment.user && comment.user.object_id  


Practice the above mentioned statements in irb.

Hope you like this.

Thank you

Naming Conventions and Boolean Expressions in Ruby


Hi  Readers,

Remember these things while coding in Ruby. Naming convention is important for good programmer, once you wrote the code it should be in systematic way.

Naming Conventions:

  • MyClass
  • method_name, destructive_method!, question_method?, setter_method=
  • MY_CONSTANT = 3.14
  • local_variable = 3.14
  • @instance_variable
  • @@class_variable
  • $global_variable
Just check your previous code in ruby is written in this naming convention format or not. Practice the naming convention coding to better and clean understanding to others also.

Boolean Expressions:

  • All objects evaluate to true except false and nil
  • false and true are the only instances of FalseClass and TrueClass
  • Boolean expressions return the last evaluated object
  • a and b or c <=> (a and b) or c
  • a = b and c <=> (a = b) and c
  • a = b && c <=> a = (b && c)
  • puts a if a = b # Using assignments in boolean expressions
  • a = true; b = false; a and b and c() # => c() is never invoked
 Good to know the details about the boolean expressions, why because in my experience i face lot of issues with boolean expressions, i found that lot of bugs reported in my past projects most of the bugs having the issue with boolean expressions, So get hands on experience on boolean expression.

Thank for reading.

If you like follow this blog.

Singleton Classes and Methods


Hi Readers,

In this post/page we are going to learn about singleton classes and their methods.

Example:

    require 'person' 
     
    # Every object has two classes: the class of which it is an instance, 
    # and a singleton class. 
    # Methods of the singleton class are called singleton methods 
    # and can only be invoked on that particular object. 
    andreas = Person.new("Andreas") 
    def andreas.andreas_says_hi 
      "Andreas says hi" 
    end 
    andreas.andreas_says_hi 
     
    # Class methods are singleton methods on the class 
    # object and can be defined like this: 
    def Person.count 
      @@count ||= 0 
    end 
    puts Person.count 


In our previous sessions example person class requiring in this, and we are defining a method with the class instance. So here Person in singleton class.

Just go through this example and practice it.

If you like follow the blog.

Thank you.

Tuesday 31 May 2016

Ruby class methods



Hi Readers,

In this post you are going to learn how to define class methods and how to call those methods.

If you want to define a class method there are two ways.

1. Inside the class by using the self keyword
2. Inside the class by using "class << self"

Refer the below example to get the Info.

  class Person 
      def self.class_method 
        puts "class method invoked" 
      end 
     
      class << self 
        def class_method2; puts "class_method2"; end 
        def class_method3; puts "class_method3"; end 
      end 
    end 
     
    class << Person 
      def class_method4; puts "class_method4"; end 
    end 
     
    # Invocation of class method 
    Person.class_method


Just practice this, i will come back with new concept.
To get more updates subscribe and follow my blog.
Thank you

Ruby Methods



 Hi Readers,
   Today we will know about the Ruby methods and parenthesis:
  1. When invoking a method argument parenthesis are optional
  2. Methods always have a receiver. The implicit receiver is self.
  3. Methods are identified by their name only. No overloading on argument signatures.
  4. There are class methods and instance methods
  5. Methods can be public, protected, or private
  6. The last evaluated expression in a method is the return value
  7. Arguments can have default values: def my_method(a, b = {})

Methods and Parenthesis:


    def square(number) 
      number * number 
    end 
     
    square(2+2)*2 # => square(4)*2 = 32 
    square (2+2)*2 # => square(4*2) = 64

Method Visibility:

    class MyClass   
      def method1 # Methods are public by default 
      end   
      # Protected methods can be invoked by any instance of the same class or a 
      # subclass of MyClass 
      protected   
      def method2 
      end 
      # Private methods can only be invoked within an instance of MyClass or a subclass 
      # of MyClass. The receiver of a private method is always self. 
      private   
      def method3 
      end 
    end  


 Hope you will understood, in next session i will come up with new concept.

Do you like my posts follow this blog by clicking the Follow button About me in right side menu.

Thank you.

Variable/Method Ambiguity Gotcha


In the below mentioned program we are defining a variable called paid, while initializing the class object we are creating instance variable default value is false.

We have make_payment instance method defined here and inside that method we assigning value to the paid variable to true, just notice that in this method we are not overriding/replacing the actual instance variable so after calling the make_payment actual instance variable value won't change, if you try to print the paid value of instance will be false.

  1.  
  2. class Person  
  3.   attr_accessor :paid  
  4.     
  5.   def initialize  
  6.     @paid = false  
  7.   end  
  8.     
  9.   def make_payment  
  10.     puts "making payment..."  
  11.     paid = true  
  12.   end  
  13. end  
  14.   
  15. person = Person.new  
  16. person.make_payment  
  17. puts "paid=#{person.paid}" 
  18.  


Try to execute the above code and practice it by changing the variables.

Hope you will understand, i will get back to you with new concept.

Ruby Attr_accessor


You can declare the attributes for the ruby class using the keyword 'attr_accessor'.

While initializing object you can assign the value to it. Check the following example and practice it.

  1. class Person  
  2.   attr_accessor :name  
  3.     
  4.   def initialize(name)  
  5.     self.name = name  
  6.   end  
  7. end  
  8.   
  9. person = Person.new("Andreas")  
  10. puts person.name  
  11. person.name = "David"  
  12. puts person.name  

Hope you will practice it, i will get back to you with new concept.

Monday 30 May 2016

Ruby creator(Yukihiro Matsumoto) talk in Rubyconf India

My Experience in RUBYCONF INDIA 2016

Hi Readers,

Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 march 2016. This was great opportunity to meet lot of rubiest.

I met lot of people who are started their career freshly and they want to share their opinions. Actually me and my friend went there 18 march afternoon, that was actual check in time they mentioned in the website.

That was nice hosting provided by le meridian hotel management. Food and accommodation was good. 18 march my friend me were having dinner that is around 9:00 P.m i think, My friend looking at one person standing in the dining hall and everyone wishing him to welcome India.

Finally my friend telling me that "Hey, he is Ruby creator 'Yukihiro Matsumoto'". Everyone calling him Matz. He is very simple and looking so tiered. Me and my friend went there to welcome him and take a photograph with him. Finally me and my friend got the photo of him.

Me and Yukihiro Matsumoto
Next day 19 march actual conference started, First talk was given by Matz, that was awesome, it went like funny and interesting. Matz was promising that in the next version of the ruby is going be more powerful, mainly his team focusing on the performance part there is no new features are introducing.

I observe that lot of people came to conf but most of them from Bengaluru, that to there are many startups of-course i am also one of them.

Some of the talks were boring and few of them are interesting. i am writing this things because i want share with you guys.




Getter and Setter Methods



In my previous posts you learn about the class and inheritance
Now we are going to get the information regarding the setter and getter methods of a ruby class

    class Person  
      def initialize(name)  
        self.name = name  
      end  
      def name  
        @name  
      end  
      def name=(name)  
        @name = name  
      end  
    end  
      
    person = Person.new("Andreas")  
    puts person.name  
    person.name = "David"  
    puts person.name  


In the above person class name definition is the one contains setter and getter methods.

In next post we will learn what attr_accessor.

Class Inheritance


Continue with previous post

require 'person_class'  
  
class Programmer < Person  
  def initialize(name, favorite_ide)  
    super(name)  
    @favorite_ide = favorite_ide  
  end  
  
  # We are overriding say_hi in Person  
  def say_hi  
    super  
    puts "Favorite IDE is #{@favorite_ide}"  
  end  
end  
  
peter = Programmer.new("Peter", "TextMate")  
peter.say_hi


In the above mentioned class we are creating a class called Programmer and inheriting the Person class which is created in previous post.

In the Programmer class we are overriding the "say_hi" definition which is all ready defined in the Person class.

Practice this code and give me the output result as comment.

<<Back

In next you are going to setter and getter methods in ruby. 

Defining a Class and Instantiating an Object


Ruby Class:

class Person  
  def initialize(name)  
    @name = name  
  end  
  
  def say_hi  
    puts "#{@name} says hi"  
  end  
end  
  
andreas = Person.new("Andreas")  
andreas.say_hi

After writing this code in file create filename with .rb extenstion.
In you command line execute the file:


> ruby example.rb 

Andreas says hi 

Just practice this In next post we will learn Class Inheritance.

Back to Ruby Introduction >> click

Ruby Introduction

Ruby

"I always thought Smalltalk would beat Java. I just didn’t know it would be called ‘Ruby’ when it did”
- Kent Beck

Ruby Language:

  • Generic, interpreted, reflective, with garbage collection
  • Optimized for people rather than computers
  • More powerful than Perl, more object oriented than Python
  • Everything is an object. There are no primitive types.
  • Strong dynamic typing

Everything in Ruby is:

  • Assignment – binding names to objects
  • Control structures – if/else, while, case
  • Sending messages to objects – methods

Ruby is Line Oriented

  • Statements are separated by line breaks
  • You can put several statements on one line if you separate them by semicolon
  • For long statements you can escape the line break with backslash
  • After an operator, comma, or the dot in a method invocation you can have a line break and Ruby will know that the statement continues on the next line
  • You can have line breaks in strings

For Quick Start follow the link:


 In next post you will get introduction of Ruby class.

Myself



Hi Readers,

My name is Shaikshavali, you can call me simply "shaik".
From last two months in my mind always thinking about to write a blog where i can share my knowledge, thoughts etc,. Finally it comes true through this blog.
I am working in a company as a Ruby on Rails developer.

In my work experience i met lot of people, Some of them are inspired me to do something better for the society. Recently i created a website called www.knowgovtdata.com. Currently this website contains hospitals, blood banks and Pin codes details of India.

My intension is to Netizens can get all this info from one site. Then they can easily find the details inform the people who are in need.

Thanks

Hope you may get some info in future posts.

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...