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

No comments:

Post a Comment

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...