RUBY Programming Introduction

download RUBY Programming Introduction

of 13

description

AMC Squarelearning Bangalore is the best training institute for a career development. it had students from various parts of the country and even few were from West African countries.

Transcript of RUBY Programming Introduction

  • What is Ruby?An interpreted language a.k.a dynamic, scriptinge.g., perlObject OrientedSingle inheritanceHigh levelGood support for system calls, regex and CGIRelies heavily on convention for syntax

  • Hello World#!/usr/bin/env ruby

    puts Hello world

    $ chmod a+x helloWorld.rb$ helloWorld.rbHello world$ shell script directive to run rubyNeeded to run any shell scriptCall to method puts to write out Hello world with CR

    Make program executable

  • Basic RubyEverything is an objectVariables are not typedAutomatic memory allocation and garbage collectionComments start with # and go to the end of the lineYou have to escape \# if you want them elsewhereCarriage returns mark the end of statementsMethods marked with def end

  • Control structuresIfelsifelseendcase when then else end

    unless endwhile enduntil end

    #.times (e.g. 5.times())#.upto(#) (e.g. 3.upto(6))

    .each {block}elsif keeps blocks at same levelcase good for checks on multiple values of same expression; can use ranges

    grade = case score when 90..100 then A when 80..90 then B else C end

    Looping constructs use end (same as class definitions)

    Various iterators allow code blocks to be run multiple times

  • Ruby Naming ConventionsInitial charactersLocal variables, method parameters, and method names lowercase letter or underscoreGlobal variable $Instance variable @Class variable @@Class names, module names, constants uppercase letterMulti-word namesInstance variables separate words with underscoresClass names use MixedCase End characters? Indicates method that returns true or false to a query! Indicates method that modifies the object in place rather than returning a copy (destructive, but usually more efficient)

  • Another Exampleclass Temperature Factor = 5.0/9

    def store_C(c) @celsius = c end

    def store_F(f) @celsius = (f - 32)*Factor end

    def as_C @celsius end

    def as_F (@celsius / Factor) + 32 endend # end of class definition Factor is a constant5.0 makes it a float

    4 methods that get/set an instance variable

    Last evaluated statement is considered the return value

  • Second Tryclass Temperature Factor = 5.0/9 attr_accessor :c

    def f=(f) @c = (f - 32) * Factor end

    def f (@c / Factor) + 32 end

    def initialize (c) @c = c endend

    t = Temperature.new(25)puts t.f # 77.0t.f = 60 # invokes f=()puts t.c # 15.55attr_accessor creates setter and getter methods automatically for a class variable

    initialize is the name for a classes constructor

    Dont worry - you can always override these methods if you need to

    Calls to methods dont need () if unambiguous

  • Input and Output - tsv filesf = File.open ARGV[0]while ! f.eof? line = f.gets if line =~ /^#/ next elsif line =~ /^\s*$/ next else puts line endendf.closeARGV is a special array holding the command-line tokens

    Gets a lineIf its not a comment or a blank linePrint it

  • Processing TSV filesh = Hash.newf = File.open ARGV[0]while ! f.eof? line = f.gets.chomp if line =~ /^\#/ next elsif line =~ /^\s*$/ next else tokens = line.split /\t/ h[tokens[2]] = tokens[1] endendf.close

    keys = h.keys.sort {|a,b| a b}keys.each {|k| puts "#{k}\t#{h[k]}" }Declare a hash tableGet lines without \n or \r\n - chompsplit lines into fields delimited with tabsStore some data from each field into the hash

    Sort the keys - sort method takes a block of code as inputeach creates an iterator in which k is set to a value at each pass#{} outputs the evaluated expression in the double quoted string

  • BlocksAllow passing chunks of code in to methodsReceiving method uses yield command to call passed code (can call yield multiple times)

    Single line blocks enclosed in {}Multi-line blocks enclosed in doend

    Can use parameters[ 1, 3, 4, 7, 9 ].each {|i| puts i }Keys = h.keys.sort {|a,b| a b }

  • Running system commandsrequire 'find'

    Find.find('.') do |filename| if filename =~ /\.txt$/i url_output = filename.gsub(/\.txt$/i, ".html") url = `cat #{filename}`.chomp cmd = "curl #{url} -o #{url_output}"; puts cmd `#{cmd}` endendrequire reads in another ruby file - in this case a module called Find

    Find returns an array, we create an iterator filename to go thru its instancesWe create a new variable to hold a new filename with the same base but different .html extensionWe use backticks `` to run a system command and (optionally) save the output into a variable curl is a command in mac os to retrieve a URL to a file, like wget in unix

  • CGI examplerequire 'cgi'

    cgi = CGI.new("html3")size = cgi.params.size

    if size > 0 # processing form in = cgi.params['t'].first.untaint cgi.out { cgi.html { cgi.head cgi.body { "Welcome, #{in}!" } } }else puts

  • Reflection...to examine aspects of the program from within the program itself.

    #print out all of the objects in our systemObjectSpace.each_object(Class) {|c| puts c}

    #Get all the methods on an objectSome String.methods

    #see if an object responds to a certain methodobj.respond_to?(:length)

    #see if an object is a typeobj.kind_of?(Numeric)obj.instance_of?(FixNum)

    *************