ruby training day1

31
Introduction To Ruby Programming Bindesh Vijayan

Upload: bindesh-vijayan

Post on 15-May-2015

171 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: Ruby training day1

Introduction To Ruby Programming

Bindesh Vijayan

Page 2: Ruby training day1

Ruby as OOPs

● Ruby is a genuine Object oriented programming

● Everything you manipulate is an object

● And the results of the manipulation is an object

● e.g. The number 4,if used, is an object

Irb> 4.classFixnum

Python : len()Ruby: obj.length

Page 3: Ruby training day1

Setting up and installing ruby

● There are various ways of installing ruby● RailsInstaller for windows and osx (http://railsinstaller.org)

● Compiling from source

● Using a package manager like rvm..most popular

Page 4: Ruby training day1

Ruby version manager(rvm)

● In the ruby world, rvm is the most popular method to install ruby and rails

● Rvm is only available for mac os x,linux and unix

● Rvm allows you to work with multiple versions of ruby

● To install rvm you need to have the curl program installed

Page 5: Ruby training day1

Installing rvm(linux)$ sudo apt-get install curl $ curl -L https://get.rvm.io | bash -s stable –ruby

$ rvm requirements

$ rvm install 1.9.3

Page 6: Ruby training day1

Standard types - numbers

● Numbers

● Ruby supports integers and floating point numbers

● Integers within a certain range (normally -230 to 230-1 or -262 to 262-1) are held internally in binary form, and are objects of class Fixnum

● Integers outside the above range are stored in objects of class Bignum

● Ruby automatically manages the conversion of Fixnum to Bignum and vice versa

● Integers in ruby support several types of iterators

Page 7: Ruby training day1

Standard types- numbers

● e.g. Of iterators● 3.times { print "X " }● 1.upto(5) { |i| print i, " " }

● 99.downto(95) { |i| print i, " " }

● 50.step(80, 5) { |i| print i, " " }

Page 8: Ruby training day1

Standard types - strings

● Strings in ruby are simply a sequence of 8-bit bytes

● In ruby strings can be assigned using either a double quotes or a single quote● a_string1 = 'hello world'

● a_string2 = “hello world”

● The difference comes

● when you want to use a special character e.g. An apostrophe● a_string1 = “Binn's world”

● a_string2 = 'Binn\'s world' # you need to use an escape sequence here

Page 9: Ruby training day1

Standard types - string

● Single quoted strings only supports 2 escape sequences, viz.● \' - single quote● \\ - single backslash

● Double quotes allows for many more escape sequences

● They also allow you to embed variables or ruby code commonly called as interpolation

puts "Enter name"name = gets.chompputs "Your name is #{name}"

Page 10: Ruby training day1

Standard types - string

Common escape sequences available are :

● \" – double quote● \\ – single backslash● \a – bell/alert● \b – backspace● \r – carriage return● \n – newline● \s – space● \t – tab

Page 11: Ruby training day1

Working with stringsgsub Returns a copy of str with

all occurrences of pattern replaced with either replacement or the value of the block.

str.gsub( pattern, replacement )

chomp Returns a new String with the given record separator removed from the end of str (if present).

str.chomp

count Return the count of characters inside string

str.count

strip Removes leading and trailing spaces from a string

str.strip

to_i Converts the string to a number(Fixnum)

str.to_i

upcase Upcases the content of the strings

str.upcase

http://www.ruby-doc.org/core-1.9.3/String.html#method-i-strip

Page 12: Ruby training day1

Standard types - ranges

● A Range represents an interval—a set of values with a start and an end

● In ruby, Ranges may be constructed using the s..e and s...e literals, or with Range::new

● ('a'..'e').to_a #=> ["a", "b", "c", "d", "e"]

● ('a'...'e').to_a #=> ["a", "b", "c", "d"]

Page 13: Ruby training day1

Using ranges

● Comparison● (0..2) == (0..2) #=> true

● (0..2) == Range.new(0,2) #=> true

● (0..2) == (0...2) #=> false

Page 14: Ruby training day1

Using ranges

● Using in iteration

(10..15).each do |n|

print n, ' '

end

Page 15: Ruby training day1

Using ranges

● Checking for members● ("a".."z").include?("g") # -> true● ("a".."z").include?("A") # -> false

Page 16: Ruby training day1

Methods● Methods are defined using the def keyword

● By convention methods that act as a query are often named in ruby with a trailing '?'● e.g. str.instance_of?

● Methods that might be dangerous(causing an exception e.g.) or modify the reciever are named with a trailing '!'● e.g. user.save!

● '?' and '!' are the only 2 special characters allowed in method name

Page 17: Ruby training day1

Defining methods

● Simple method:

def mymethod

end

● Methods with arguments:

def mymethod2(arg1, arg2)

end

● Methods with variable length arguments

def varargs(arg1, *rest)

"Got #{arg1} and #{rest.join(', ')}"

end

Page 18: Ruby training day1

Methods● In ruby, the last line of the method statement is returned back and there is no need to explicitly use a return statement

def get_message(name)

“hello, #{name}”

end

.Calling a method :

get_message(“bin”)

● Calling a method without arguments :

mymethod #calls the method

Page 19: Ruby training day1

Methods with blocks

● When a method is called, it can be given a random set of code to be executed called as blocks

def takeBlock(p1)

if block_given?

yield(p1)

else

p1

end

end

Page 20: Ruby training day1

Calling methods with blocks

takeBlock("no block") #no block provided

takeBlock("no block") { |s| s.sub(/no /, '') }

Page 21: Ruby training day1

Classes

● Classes in ruby are defined by using the keyword 'class'

● By convention, ruby demands that the class name should be capital

● An initialize method inside a class acts as a constructor

● An instance variable can be created using @

Page 22: Ruby training day1

class Book

def intitialize(title,author) @title = title @author = author end

end

//creating an object of the class

b1 = Book.new("programming ruby","David")

class SimpleClass

end

//instantiate an object

s1 = SimpleClass.new

Page 23: Ruby training day1

Making an attribute accessible

● Like in any other object oriented programming language, you will need to manipulate the attributes

● Ruby makes this easy with the keyword 'attr_reader' and 'attr_writer'

● This defines the getter and the setter methods for the attributes

Page 24: Ruby training day1

class Book

attr_reader :title, :author

def initialize(title,author)@title = title@author = author

end

end

#using gettersCompBook = Book.new(“A book”, “me”)Puts CompBook.title

Page 25: Ruby training day1

Symbols● In ruby symbols can be declared using ':'● e.g :name● Symbols are a kind of strings ● The important difference is that they are immutable

unlike strings● Mutable objects can be changed after assignment while

immutable objects can only be overwritten. ● puts "hello" << " world"● puts :hello << :" world"

Page 26: Ruby training day1

Making an attribute writeable

class Book

attr_writer :title, :author def initialize(title,author)

@title = title@author = author

end

end myBook = Book.new("A book", "author")

myBook.title = "Some book"

Page 27: Ruby training day1

Class variables

● Sometimes you might need to declare a class variable in your class definition

● Class variables have a single copy for all the class objects

● In ruby, you can define a class variable using @@ symbol

● Class variables are private to the class so in order to access them outside the class you need to defined a getter or a class method

Page 28: Ruby training day1

Class Methods

● Class methods are defined using the keyword self

● e.g. – def self.myclass_methodend

Page 29: Ruby training day1

Exampleclass SomeClass

@@instance = 0 #privateattr_reader :instance

def initialize@@instance += 1

end

def self.instances @@instanceend

end

s1 = SomeClass.new s2 = SomeClass.new

puts "total instances #{SomeClass.instances}"

Page 30: Ruby training day1

Access Control

● You can specify 3 types of access control in ruby● Private

● Protected● Public

● By default, unless specified, all methods are public

Page 31: Ruby training day1

class Program

def get_sumcalculate_internal

end

private def calculate_internalend

end

Access Control-Example