Ruby

What is Ruby ?

Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan.
You can find the name Yukihiro Matsumoto on the Ruby mailing list at www.ruby-lang.org. Matsumoto is also known as Matz in the Ruby community.
Ruby is "A Programmer's Best Friend".
Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is a perfect object-oriented language. Using Ruby syntax is much easier than using Smalltalk syntax.
Features of Ruby
  • Ruby is an open-source and is freely available on the Web, but it is subject to a license.
  • Ruby is a general-purpose, interpreted programming language.
  • Ruby is a true object-oriented programming language.
  • Ruby is a server-side scripting language similar to Python and PERL.
  • Ruby can be used to write Common Gateway Interface (CGI) scripts.
  • Ruby can be embedded into Hypertext Markup Language (HTML).
  • Ruby has a clean and easy syntax that allows a new developer to learn Ruby very quickly and easily.
  • Ruby has similar syntax to that of many programming languages such as C++ and Perl.
  • Ruby is very much scalable and big programs written in Ruby are easily maintainable.
  • Ruby can be used for developing Internet and intranet applications.
  • Ruby can be installed in Windows and POSIX environments.
  • Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL.
  • Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase.
  • Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts

Simple Ruby Program for Beginners
1.CLASS and METHOD Program

class Sample

    @@nam = "bishnu"
    $age = 50
    sam = "sample"
    puts"this is from #{sam} class"
#method   
def test
   
    puts"my name is #@@nam"
    puts"i am #$age yr old"
    end
#method
    def test1(a = "ramesh", b = "suresh")
    puts"a is #{a}"
    puts"b is #{b}"
    end
end
obj = Sample.new
obj1 = Sample.new
obj.test
obj.test1("joy","Jerry")
obj.test1

Output:

my name is bishnu
i am 50 yr old
a is joy
b is Jerry
a is ramesh
b is suresh

2.IF , ELSIF and ELSE Program


x = 10

if x >5 and x == 5
    puts"this is it"
    puts", i got it"
elsif x == 10
    puts"this is number :10 "
    puts"it can execute without any bracket;"
else
    puts"something wrong"
end

Output:

this is number :10 
it can execute without any bracket;

3. UNLESS and CASE Program



x = 1

unless x == 1
    puts"this is false"
=begin
elsif x == 1
    puts"from elsif"
=end
#Unless doesnt containt elsif or elsunless

else

    puts"from else"
end

#unless block execute when condition is false.

puts"........................................."

a = 5

case a
when 0..2
    puts"#{a} belongs to 0 to 2"
when 3..6
    puts"#{a} belongs to 2 to 6"
when 6..9
    puts"#{a} belongs to 6 to 9"
when 9..11
    puts"from 9 to 11"
else
    puts"not matched"
end

#if two condition satisfying it consider only first one .


Output:


from else

.........................................
5 belongs to 2 to 6

4 .BEGIN and END Block 


puts"...............BEGIN & END............ "

class Cls
    puts"from class Cls"
    END{
    puts"this end1"
    }
=begin
    BEGIN{
    puts"from begin1"
    }
# BEGIN block does not support inside method or in class
=end
def test
puts"from test"
END{
puts"end from test"
}
end
end
END{
puts"end from outside class"
}
BEGIN{
puts"begin from outside class"
}
obj = Cls.new
obj.test

#BEGIN block execute from top to bottom but the END block comes last which one execute 1st


Output:


warning: END in method; use at_exit begin from outside class

...............BEGIN & END............ 
from class Cls
from test
end from test
end from outside class
this end1

5. Array 


#!/usr/bin/ruby

class A
    def aboutArray
    puts"from aboutArray Method "
    #arr = Array.new("text")   #cant provide character with new in array .this is only for size but in hash it is possible
    arr = ['a',1,'Tom',3,"Jerry",6]
    puts"The length of array is :#{arr.length}"

    puts"#{arr}" #will display the array in one line


    puts arr  #will display the array multiple line

puts"using for loop---------------------"
        for i in 0...6
        puts"array#{[i]}: #{arr[i]}"
        end
puts"each iterator----------------------------------"
        arr.each do |i|
        puts i
        end
puts"after collection -------------------"
a = [1,3,4,5]
arr2 = Array.new
arr2 = a.collect{|v| v *2 }
puts arr2
end

end

obj = A.new
obj.aboutArray

Output:


from aboutArray Method

The length of array is :6
["a", 1, "Tom", 3, "Jerry", 6]
a
1
Tom
3
Jerry
6
using for loop---------------------
array[0]: a
array[1]: 1
array[2]: Tom
array[3]: 3
array[4]: Jerry
array[5]: 6
each iterator----------------------------------
a
1
Tom
3
Jerry
6
after collection -------------------
2
6
8
10


6.Hash

class B
   def test   

has = Hash.new

    has = {:a => 100,"b" => 200,"c" => 300}
       puts"#{has}"

has1 = Hash[:x => 500, :y => 600, :z => 700]


puts"#{has1}"


key = has.keys


puts"#{key}"


puts"#{has[:a]}"   


end

end
obj = B.new
obj.test

Output: 


{:a=>100, "b"=>200, "c"=>300}
{:x=>500, :y=>600, :z=>700}
[:a, "b", "c"]
100


Note:

# {}, if assigning values after declare.
# [], if assigning value at a time. 
# keys is hash method ,return hash keys.
# :a is symbol & "b" is string. symbol is better then string as key of hash . 


Array Methods and Description .

SNMethods with Description
1array & other_array
Returns a new array containing elements common to the two arrays, with no duplicates.
2array * int [or] array * str
Returns a new array built by concatenating the int copies of self. With a String argument, equivalent to self.join(str).
3array + other_array
Returns a new array built by concatenating the two arrays together to produce a third array.
4array - other_array
Returns a new array that is a copy of the original array, removing any items that also appear in other_array.
5str <=> other_str
Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive.
6array | other_array
Returns a new array by joining array with other_array, removing duplicates.
7array << obj
Pushes the given object onto the end of array. This expression returns the array itself, so several appends may be chained together.
8array <=> other_array
Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_array.
9array == other_array
Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object.==) the corresponding element in the other array.
10array[index] [or] array[start, length] [or]
array[range] [or] array.slice(index) [or]
array.slice(start, length) [or] array.slice(range)

Returns the element at index, or returns a subarray starting at start and continuing for lengthelements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) is out of range.
11array[index] = obj [or]
array[start, length] = obj or an_array or nil [or]
array[range] = obj or an_array or nil

Sets the element at index, or replaces a subarray starting at start and continuing for lengthelements, or replaces a subarray specified by range. If indices are greater than the current capacity of the array, the array grows automatically. Negative indices will count backward from the end of the array. Inserts elements if length is zero. If nil is used in the second and third form, deletes elements from self.
12array.abbrev(pattern = nil)
Calculates the set of unambiguous abbreviations for the strings in self. If passed a pattern or a string, only the strings matching the pattern or starting with the string are considered.
13array.assoc(obj)
Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches or nil if no match is found.
14array.at(index)
Returns the element at index. A negative index counts from the end of self. Returns nil if the index is out of range.
15array.clear
Removes all elements from array.
16array.collect { |item| block } [or]
array.map { |item| block }

Invokes block once for each element of self. Creates a new array containing the values returned by the block.
17array.collect! { |item| block } [or]
array.map! { |item| block }

Invokes block once for each element of self, replacing the element with the value returned byblock.
18array.compact
Returns a copy of self with all nil elements removed.
19array.compact!
Removes nil elements from array. Returns nil if no changes were made.
20array.concat(other_array)
Appends the elements in other_array to self.
21array.delete(obj) [or] 
array.delete(obj) { block }

Deletes items from self that are equal to obj. If the item is not found, returns nil. If the optional code block is given, returns the result of block if the item is not found.
22array.delete_at(index)
Deletes the element at the specified index, returning that element, or nil if the index is out of range.
23array.delete_if { |item| block }
Deletes every element of self for which block evaluates to true.
24array.each { |item| block }
Calls block once for each element in self, passing that element as a parameter.
25array.each_index { |index| block }
Same as Array#each, but passes the index of the element instead of the element itself.
26array.empty?
Returns true if the self array contains no elements.
27array.eql?(other)
Returns true if array and other are the same object, or are both arrays with the same content.
28array.fetch(index) [or] 
array.fetch(index, default) [or] 
array.fetch(index) { |index| block }

Tries to return the element at position index. If index lies outside the array, the first form throws anIndexError exception, the second form returns default, and the third form returns the value of invoking block, passing in index. Negative values of index count from the end of the array.
29array.fill(obj) [or]
array.fill(obj, start [, length]) [or]
array.fill(obj, range) [or]
array.fill { |index| block } [or]
array.fill(start [, length] ) { |index| block } [or]
array.fill(range) { |index| block }

The first three forms set the selected elements of self to obj. A start of nil is equivalent to zero. A length of nil is equivalent to self.length. The last three forms fill the array with the value of the block. The block is passed with the absolute index of each element to be filled.
30array.first [or] 
array.first(n)

Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, and the second form returns an empty array.
31array.flatten
Returns a new array that is a one-dimensional flattening of this array (recursively).
32array.flatten!
Flattens array in place. Returns nil if no modifications were made. (array contains no subarrays.)
33array.frozen?
Returns true if array is frozen (or temporarily frozen while being sorted).
34array.hash
Compute a hash-code for array. Two arrays with the same content will have the same hash code
35array.include?(obj)
Returns true if obj is present in self, false otherwise.
36array.index(obj)
Returns the index of the first object in self that is == to obj. Returns nil if no match is found.
37array.indexes(i1, i2, ... iN) [or]
array.indices(i1, i2, ... iN)

This methods is deprecated in latest version of Ruby so please use Array#values_at.
38array.indices(i1, i2, ... iN) [or]
array.indexes(i1, i2, ... iN)

This methods is deprecated in latest version of Ruby so please use Array#values_at.
39array.insert(index, obj...)
Inserts the given values before the element with the given index (which may be negative).
40array.inspect
Creates a printable version of array.
41array.join(sep=$,)
Returns a string created by converting each element of the array to a string, separated by sep.
42array.last [or] array.last(n)
Returns the last element(s) of self. If array is empty, the first form returns nil.
43array.length
Returns the number of elements in self. May be zero.
44array.map { |item| block } [or]
array.collect { |item| block }

Invokes block once for each element of self. Creates a new array containing the values returned by the block.
45array.map! { |item| block } [or]
array.collect! { |item| block }

Invokes block once for each element of array, replacing the element with the value returned by block.
46array.nitems
Returns the number of non-nil elements in self. May be zero.
47array.pack(aTemplateString)
Packs the contents of array into a binary sequence according to the directives in aTemplateString. Directives A, a, and Z may be followed by a count, which gives the width of the resulting field. The remaining directives also may take a count, indicating the number of array elements to convert. If the count is an asterisk (*), all remaining array elements will be converted. Any of the directives is still may be followed by an underscore (_) to use the underlying platform's native size for the specified type; otherwise, they use a platformindependent size. Spaces are ignored in the template string. ( See templating Table below )
48array.pop
Removes the last element from array and returns it, or nil if array is empty.
49array.push(obj, ...)
Pushes (appends) the given obj onto the end of this array. This expression returns the array itself, so several appends may be chained together.
50array.rassoc(key)
Searches through the array whose elements are also arrays. Compares key with the second element of each contained array using ==. Returns the first contained array that matches.
51array.reject { |item| block }
Returns a new array containing the items array for which the block is not true.
52array.reject! { |item| block }
Deletes elements from array for which the block evaluates to true, but returns nil if no changes were made. Equivalent to Array#delete_if.
53array.replace(other_array)
Replaces the contents of array with the contents of other_array, truncating or expanding if necessary.
54array.reverse
Returns a new array containing array's elements in reverse order.
55array.reverse!
Reverses array in place.
56array.reverse_each {|item| block }
Same as Array#each, but traverses array in reverse order.
57array.rindex(obj)
Returns the index of the last object in array == to obj. Returns nil if no match is found.
58array.select {|item| block }
Invokes the block passing in successive elements from array, returning an array containing those elements for which the block returns a true value.
59array.shift
Returns the first element of self and removes it (shifting all other elements down by one). Returnsnil if the array is empty.
60array.size
Returns the length of array (number of elements). Alias for length.
61array.slice(index) [or] array.slice(start, length) [or]
array.slice(range) [or] array[index] [or]
array[start, length] [or] array[range]

Returns the element at index, or returns a subarray starting at start and continuing for lengthelements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) are out of range.
62array.slice!(index) [or] array.slice!(start, length) [or]
array.slice!(range)

Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object, subarray, or nil if index is out of range.
63array.sort [or] array.sort { | a,b | block }
Returns a new array created by sorting self.
64array.sort! [or] array.sort! { | a,b | block }
Sorts self.
65array.to_a
Returns self. If called on a subclass of Array, converts the receiver to an Array object.
66array.to_ary
Returns self.
67array.to_s
Returns self.join.
68array.transpose
Assumes that self is an array of arrays and transposes the rows and columns.
69array.uniq
Returns a new array by removing duplicate values in array.
70array.uniq!
Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
71array.unshift(obj, ...)
Prepends objects to the front of array, other elements up one.
72array.values_at(selector,...)
Returns an array containing the elements in self corresponding to the given selector (one or more). The selectors may be either integer indices or ranges.
73array.zip(arg, ...) [or] 
array.zip(arg, ...){ | arr | block }

Converts any arguments to arrays, then merges elements of array with corresponding elements from each argument.

Comments

  1. class Nishi
    def change
    c = 2+2
    puts "#{c}"
    yield
    d = 3*3
    puts"#{d}"
    yield
    end
    end
    n = Nishi.new
    n.change{ |e = 14| puts"#{e}"}


    OP:
    4
    14
    9
    14

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple way of importing and exporting excel, csv file for ruby on rails application using roo gem

Ruby on Rails Gems Install & Implementation

Important Query for PostgreSQL