"Jimmy" * 5=> "JimmyJimmyJimmyJimmyJimmy" 40.to_s.reverse=> "04"
[12, 47, 35].max
array.sort! A lot of times Ruby methods shout like that if they change what the
variable contains for good. It's nothin' special, just a mark. irb(main):002:0> ticket => [1, 2, 3] irb(main):003:0> ticket.reverse => [3, 2, 1] irb(main):004:0> ticket => [1, 2, 3] irb(main):005:0> ticket.reverse! => [3, 2, 1] irb(main):006:0> ticket => [3, 2, 1] poem.lines.to_a poem.include? "my hand"=> true print poem=> "My toast has flown from my hand And my toast has gone to the moon. But when I saw it on television, Planting our flag on Halley's comet, More still did I want to eat it." Success! > poem["toast"] = "honeydew" => "honeydew" Success! > poem => "My honeydew has flown from my hand And my toast has gone to the moon. But when I saw it on television, Planting our flag on Halley's comet, More still did I want to eat it." >
Install ruby mac $ \curl -L https://get.rvm.io | bash -s stable --ruby $ source /Users/morteza/.rvm/scripts/rvm $ rvm $ gem install rails $ rails new blog2 $ cd blog2/ $ rails s $ bundle update; bundle install
addition = lambda {|a, b| return a + b }s puts addition.call(5, 6) $ irb >> "hello world" => "hello world" >> puts "Hello World" Hello World => nil >> 3+2 => 5 >> Math.sqrt(9) => 3.0 | >> def h >> puts "Hello World" >> end => nil >> h Hello World | >> def h(name="World") >> puts "Hello #{name.capitalize}" >> end => nil >> h Hello World => nil >> h "Morteza" Hello MORTEZA => nil
# any expression
| >> class Greeter >> def initialize(name="World") >> @name = name >> end >> def say_hi >> puts "Hi #{@name}" >> end >> def say_bye >> end >> end => nil >> g = Greeter.new("Pat") => #<Greeter:0x10375abf8 @name="Pat"> >> g => #<Greeter:0x10375abf8 @name="Pat"> >> g.say_hi Hi Pat => nil >>
@ determines instance variable
| >> Greeter.instance_methods >>
["inspect", "tap", "clone", "h", "public_methods", "__send__",
"instance_variable_defined?", "equal?", "freeze", "extend", "send",
"methods", "hash", "dup", "object_id", "instance_variables", "say_hi",
"eql?", "instance_eval", "id", "singleton_methods", "taint", "frozen?",
"instance_variable_get", "to_enum", "instance_of?", "display", "to_a",
"say_bye", "type", "instance_exec", "protected_methods", "==", "===",
"instance_variable_set", "enum_for", "kind_of?", "respond_to?",
"method", "to_s", "class", "__id__", "tainted?", "=~",
"private_methods", "untaint", "nil?", "is_a?"]
>> Greeter.instance_methods false => ["say_hi", "say_bye"] do not print inherited methods, below check out which methods it has
>> g.respond_to?("name") => false >> g.respond_to?("say_hi") => true >> g.respond_to?("to_s") => true open up the class, modify it >> class Greeter >> attr_accessor :name >> end => nil >> g.name => "Andy" >> g.name="Betsy" => "Betsy" >> g.name => "Betsy"
attr_accessor ceates getter and setter=
|
#comment
multiline comment: =begin
This is a comment.
This is a comment, too.
This is a comment, too.
I said that already.
=end
change class declaration on the fly, current and new instances will be affected. BEGIN {
code
}
Declares code to be called before the program is run.
END {
code
}
Declares code to be called at the end of the program. Variables in a Ruby Class:
Ruby provides four types of variables:
Local Variables: Local variables are the variables that
are defined in a method. Local variables are not available outside the
method. You will see more detail about method in subsequent chapter.
Local variables begin with a lowercase letter or _. Instance Variables: Instance variables are available
across methods for any particular instance or object. That means that
instance variables change from object to object. Instance variables are
preceded by the at sign (@) followed by the variable name. Class Variables: Class variables are available across
different objects. A class variable belongs to the class and is a
characteristic of a class. They are preceded by the sign @@ and are
followed by the variable name. Global Variables: Class variables are not available across
classes. If you want to have a single variable, which is available
across classes, you need to define a global variable. The global
variables are always preceded by the dollar sign ($).
To create an object call .new method of class cust1=Customer.new("1", "John", "Wisdom Apartments") class Customer
@@no_of_customers=0
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
end self: The receiver object of the current method. true: Value representing true. false: Value representing false. nil: Value representing undefined. __FILE__: The name of the current source file. __LINE__: The current line number in the source file.
but single-quoted strings don't allow substitution and allow backslash notation only for \\ and \'
Array
ary = [ "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
puts i
end
Hashhsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
print key, " is ", value, "\n"
end
books["Gravity's Rainbow"] = :splendid => :splendid > books => {"Gravity's Rainbow"=>:splendid}
Range(1..5).each do |i| puts i end 12345 (1...5).each do |i| puts i end 1234
<=> | Combined comparison
operator. Returns 0 if first operand equals second, 1 if first operand
is greater than the second and -1 if first operand is less than the
second. | (a <=> b) returns -1. |
=== | Used to test equality within a when clause of a case statement. | (1...10) === 5 returns true. |
.eql? | True if the receiver and argument have both the same type and equal values. | 1
== 1.0 returns true, but 1.eql?(1.0) is false. |
equal? | True if the receiver and argument have the same object id. | if aObj is duplicate of bObj then aObj == bObj is true, a.equal?bObj is false but a.equal?aObj is true. |
defined? is a special operator that takes the form of a method call
to determine whether or not the passed expression is defined. It returns
a description string of the expression, or nil if the expression isn't defined. foo = 42
defined? foo # => "local-variable"
defined? $_ # => "global-variable"
defined? bar # => nil defined? puts # => "method"
defined? puts(bar) # => nil (bar is not defined here)
defined? unpack # => nil
ModuleYou call a module method by preceding its name with the module's name
and aperiod, and you reference a constant using the module name and two
colons. MR_COUNT = 0 # constant defined on main Object class
module Foo
MR_COUNT = 0
::MR_COUNT = 1 # set global count to 1
MR_COUNT = 2 # set local count to 2
end
puts MR_COUNT # this is the global constant
puts Foo::MR_COUNT # this is the local "Foo" constant | |
if x=1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end print "debug\n" if $debug case/when case expr0
when expr1, expr2
stmt1
when expr3, expr4
stmt2
else
stmt3
end
is basically similar to the following:
_tmp = expr0
if expr1 === _tmp || expr2 === _tmp
stmt1
elsif expr3 === _tmp || expr4 === _tmp
stmt2
else
stmt3
end | $age = 5
case $age
when 0 .. 2
puts "baby"
when 3 .. 6
puts "little child"
when 7 .. 12
puts "child"
when 13 .. 18
puts "youth"
else
puts "adult"
end |
Loop
$i = 0 $num = 5 while $i < $num do
puts("i = #$i" ) $i +=1
end
code while condition OR begin code end while conditional
|
for i in 0..5 puts "i = #{i}" end |
(0..5).each do |i| puts "i = #{i}" end |
begin do_something # exception raised rescue # handles error retry # restart from beginning end | for i in 1..5 retry if i > 2 #if as a modifier puts "Value of local variable is #{i}" end
This will produce following result and will go in an infinite loop: Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 ............................
|
redo
Restarts this iteration of the most internal loop, without checking
loop condition. Restarts yield or call if called within a block. MethodsEvery method in Ruby returns a value by default. This returned value will be the value of the last statement.
return [expr[`,' expr...]] If
more than two expressions are given, the array contains these values
will be the return value. If no expression given, nil will be the return
value.
def sample (*test) puts "The number of parameters is #{test.length}" for i in 0...test.length puts "The parameters are #{test[i]}" end end sample "Zara", "6", "F" sample "Mac", "36", "M", "MCA" In
this code, you have declared a method sample that accepts one parameter
test. However, this parameter is a variable parameter. This means that
this parameter can take in any number of variables.
class methodsclass Accounts def reading_charge end def Accounts.return_date end end See
how the method return_date is declared. It is declared with the class
name followed by a period, which is followed by the name of the method.
You can access this class method directly as follows: Accounts.return_date
give alias to methods or global variables. alias method-name method-name
alias global-variable-name global-variable-name YieldYield: block calling like method calling or method pass as parameter def test
yield 5
puts "You are in the method test"
yield 100
end
test {|i| puts "You are in the block #{i}"} You have seen how how a block and a method can be associated with
each other.You normally invoke a block by using the yield statement from
a method that has the same name as that of the block. Therefore, you
write:
def test
yield
end
test{ puts "Hello world"} Module Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.
Mixin (multiple inheritance) module A
def a1
end
def a2
end
def b2
end end
module B
def b1
end
def b2
end
end
class Sample
include A
include B
def s1
end
end
samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2 => B.b2
samp.s1
items of the same name will be overwritten. here
More on Strings %{Ruby is fun.} equivalent to "Ruby is fun."
%Q{ Ruby is fun. } equivalent to " Ruby is fun. "
%q[Ruby is fun.] equivalent to a single-quoted string
%x!ls! equivalent to back tick command output `ls` SN | Methods with Description |
1 | str % arg Formats a string using a format
specification. arg must be an array if it contains more than one
substitution. For information on the format specification. see sprintf
under "Kernel Module." |
2 | str * integer Returns a new string containing integer times str. In other words, str is repeated integer imes. |
3 | str + other_str Concatenates other_str to str. |
4 | str << obj Concatenates an object to
str. If the object is a Fixnum in the range 0.255, it is converted to a
character. Compare it with concat. |
5 | str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive. |
6 | str == obj Tests str and obj for equality. If obj is not a String, returns false; returns true if str <=> obj returns 0. |
7 | str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise,
false. |
8 | str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise,
false. |
9 | str.capitalize Capitalizes a string. |
10 | str.capitalize! Same as capitalize, but changes are made in place. |
11 | str.casecmp Makes a case-insensitive comparison of strings. |
12 | str.center Centers a string. |
13 | str.chomp Removes the record separator ($/), usually \n, from the end of a string. If no record separator exists, does nothing. |
14 | str.chomp! Same as chomp, but changes are made in place. |
15 | str.chop Removes the last character in str. |
16 | str.chop! Same as chop, but changes are made in place. |
17 | str.concat(other_str) Concatenates other_str to str. |
18 | str.count(str, ...) Counts one or more sets of characters. If there is more than one set of characters, counts the intersection of those sets |
19 | str.crypt(other_str) Applies a one-way
cryptographic hash to str. The argument is the salt string, which should
be two characters long, each character in the range a.z, A.Z, 0.9, . or
/. |
20 | str.delete(other_str, ...) Returns a copy of str with all characters in the intersection of its arguments deleted. |
21 | str.delete!(other_str, ...) Same as delete, but changes are made in place. |
22 | str.downcase Returns a copy of str with all uppercase letters replaced with lowercase. |
23 | str.downcase! Same as downcase, but changes are made in place. |
24 | str.dump Returns a version of str with all nonprinting characters replaced by \nnn notation and all special characters
escaped. |
25 | str.each(separator=$/) { |substr| block } Splits str using argument as the record separator ($/ by
default), passing each substring to the supplied block. |
26 | str.each_byte { |fixnum| block } Passes each byte from str to the block, returning each byte as a decimal representation of the byte. |
27 | str.each_line(separator=$/) { |substr| block } Splits str using argument as the record separator ($/ by default), passing each substring to the supplied block. |
28 | str.empty? Returns true if str is empty (has a zero length). |
29 | str.eql?(other) Two strings are equal if the have the same length and content. |
30 | str.gsub(pattern, replacement) [or]
str.gsub(pattern) { |match| block } Returns a copy of str with
all occurrences of pattern replaced with either replacement or the value
of the block. The pattern will typically be a Regexp; if it is a String
then no regular expression metacharacters will be
interpreted (that is, /\d/ will match a digit, but '\d' will match a
backslash followed by a 'd') |
31 | str[fixnum] [or] str[fixnum,fixnum] [or] str[range] [or] str[regexp] [or] str[regexp, fixnum] [or] str[other_str] References
str, using the following arguments: one
Fixnum, returns a character code at fixnum; two Fixnums, returns a
substring starting at an offset (first fixnum) to length (second
fixnum); range, returns a substring in the range; regexp returns portion
of matched string; regexp with fixnum, returns matched data at fixnum;
other_str returns substring matching other_str. A negative Fixnum starts
at end of string with -1. |
32 | str[fixnum] = fixnum [or] str[fixnum] = new_str [or] str[fixnum, fixnum] = new_str [or] str[range] = aString [or]
str[regexp] =new_str [or] str[regexp, fixnum] =new_str [or] str[other_str] = new_str ] Replace (assign) all or part of a string. Synonym of slice!. |
33 | str.gsub!(pattern, replacement) [or] str.gsub!(pattern) { |match| block } Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. |
34 | str.hash Returns a hash based on the string's length and content. |
35 | str.hex Treats leading characters from str
as a string of hexadecimal digits (with an optional sign and an optional
0x) and returns the corresponding number. Zero is returned on error. |
36 | str.include? other_str [or] str.include? fixnum Returns true if str contains the given string or character. |
37 | str.index(substring [, offset]) [or]
str.index(fixnum [, offset]) [or]
str.index(regexp [, offset]) Returns the index of the first
occurrence of the given substring, character (fixnum), or pattern
(regexp) in str. Returns nil if not found. If the second parameter is
present, it specifies the position in the string to begin the
search. |
38 | str.insert(index, other_str) Inserts
other_str before the character at the given index, modifying str.
Negative indices count from the end of the string, and insert after the
given character. The intent is to insert a string so that it starts at
the given index. |
39 | str.inspect Returns a printable version of str, with special characters escaped. |
40 | str.intern [or] str.to_sym Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. |
41 | str.length Returns the length of str. Compare size. |
42 | str.ljust(integer, padstr=' ') If integer
is greater than the length of str, returns a new String of length
integer with str left-justified and padded with padstr; otherwise,
returns str. |
43 | str.lstrip Returns a copy of str with leading whitespace removed. |
44 | str.lstrip! Removes leading whitespace from str, returning nil if no
change was made. |
45 | str.match(pattern) Converts pattern to a Regexp (if it isn't already one), then invokes its match method on str. |
46 | str.oct Treats leading characters of str as
a string of octal digits (with an optional sign) and returns the
corresponding number. Returns 0 if the conversion fails. |
47 | str.replace(other_str) Replaces the contents and taintedness of str with the corresponding values in other_str. |
48 | str.reverse Returns a new string with the characters from str in
reverse order. |
49 | str.reverse! Reverses str in place. |
50 | str.rindex(substring [, fixnum]) [or]
str.rindex(fixnum [, fixnum]) [or]
str.rindex(regexp [, fixnum]) Returns the index of the last
occurrence of the given substring, character (fixnum), or pattern
(regexp) in str. Returns nil if not found. If the second parameter is
present, it specifies the position in the string to end the
search.characters beyond this point won't be considered. |
51 | str.rjust(integer, padstr=' ') If integer is greater than the length of str, returns a new
String of length integer with str right-justified and padded with padstr; otherwise, returns str. |
52 | str.rstrip Returns a copy of str with trailing whitespace removed. |
53 | str.rstrip! Removes trailing whitespace from str, returning nil if no change was made. |
54 | str.scan(pattern) [or]
str.scan(pattern) { |match, ...| block } Both forms iterate
through str, matching the pattern (which may be a Regexp or a String).
For each match, a result is generated and either added to the result
array or passed to the block. If the pattern contains no groups, each
individual result consists of the matched string, $&. If the pattern
contains groups, each individual result is
itself an array containing one entry per group. |
55 | str.slice(fixnum) [or] str.slice(fixnum, fixnum) [or]
str.slice(range) [or] str.slice(regexp) [or]
str.slice(regexp, fixnum) [or] str.slice(other_str)
See str[fixnum], etc.
str.slice!(fixnum) [or] str.slice!(fixnum, fixnum) [or]
str.slice!(range) [or] str.slice!(regexp) [or]
str.slice!(other_str) Deletes the specified portion from str, and
returns the portion deleted. The forms that take a Fixnum will raise an
IndexError if the value is out of range; the Range form will raise a
RangeError, and the Regexp and String forms
will silently ignore the assignment. |
56 | str.split(pattern=$;, [limit])
Divides str into substrings based on a delimiter, returning an array of these substrings.
If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space,
str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
If pattern is a Regexp, str is divided where the pattern
matches. Whenever the pattern matches a zero-length string, str is split
into individual characters.
If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` `
were specified.
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that
number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative,
there is no limit to the number of fields returned, and trailing null fields are not suppressed. |
57 | str.squeeze([other_str]*) Builds a set of
characters from the other_str parameter(s) using the procedure described
for String#count. Returns a new string where runs of the same character
that occur in this set are replaced by a single character. If no
arguments are given, all runs of identical characters are replaced by a
single character. |
58 | str.squeeze!([other_str]*) Squeezes str in place, returning either str, or nil if no changes were made. |
59 | str.strip Returns a copy of str with leading and trailing whitespace removed. |
60 | str.strip! Removes leading and trailing whitespace from str. Returns nil if str was not altered. |
61 | str.sub(pattern, replacement) [or]
str.sub(pattern) { |match| block } Returns a copy of str with the
first occurrence of pattern replaced with either replacement or the
value of the block. The pattern will typically be a Regexp; if it is a
String then no regular expression metacharacters will be
interpreted. |
62 | str.sub!(pattern, replacement) [or]
str.sub!(pattern) { |match| block } Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed. |
63 | str.succ [or] str.next Returns the successor to str. |
64 | str.succ! [or] str.next! Equivalent to String#succ, but modifies the receiver in
place. |
65 | str.sum(n=16) Returns a basic n-bit
checksum of the characters in str, where n is the optional Fixnum
parameter, defaulting to 16. The result is simply the sum of the binary
value of each character in str modulo 2n - 1. This is not a particularly
good checksum. |
66 | str.swapcase Returns a copy of str with
uppercase alphabetic characters converted to lowercase and lowercase
characters converted to uppercase. |
67 | str.swapcase! Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. |
68 | str.to_f Returns the result of interpreting
leading characters in str as a floating-point number. Extraneous
characters past the end of a valid number are ignored. If there is not a
valid number at the start of str, 0.0 is returned. This method never
raises an exception. |
69 | str.to_i(base=10) Returns the result of
interpreting leading characters in str as an integer base (base 2, 8,
10, or 16). Extraneous characters past the end of a valid number are
ignored. If there is not a valid number at the start of str, 0 is
returned. This method never raises an exception. |
70 | str.to_s [or] str.to_str Returns the receiver. |
71 | str.tr(from_str, to_str) Returns a copy of
str with the characters in from_str replaced by the corresponding
characters in to_str. If to_str is shorter than from_str, it is padded
with its last character. Both strings may use the c1.c2 notation to
denote ranges of characters, and from_str may start with a ^, which
denotes all characters except those listed. |
72 | str.tr!(from_str, to_str) Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. |
73 | str.tr_s(from_str, to_str) Processes a copy
of str as described under String#tr, then removes duplicate characters
in regions that were affected by the translation. |
74 | str.tr_s!(from_str, to_str) Performs String#tr_s processing on str in place, returning str, or nil if no changes were made. |
75 | str.unpack(format) Decodes str (which may
contain binary data) according to the format string, returning an array
of each value extracted. The format string consists of a sequence of
single-character directives, summarized in Table 18.
Each directive may be followed by a number, indicating the number of
times to repeat with this directive. An asterisk (*) will use up all
remaining elements. The directives sSiIlL may each be followed by an
underscore (_) to use the underlying platform's native size for the
specified type; otherwise, it uses a platform-independent consistent
size. Spaces are ignored in the format string. |
76 | str.upcase Returns a copy of str with all
lowercase letters replaced with their uppercase counterparts. The
operation is locale insensitive.only characters a to z are affected. |
77 | str.upcase! Changes the contents of str to uppercase, returning nil if no changes are made. |
78 | str.upto(other_str) { |s| block } Iterates
through successive values, starting at str and ending at other_str
inclusive, passing each value in turn to the block. The String#succ
method is used to generate each value. |
Array names = Array.new(20)
#!/usr/bin/ruby
digits = Array(0..9)
num = digits.at(6)
puts "#{num}"
This will produce following result:
6
Following are the public array methods ( Assuming array is an array object ):
SN | Methods with Description |
1 | array & other_array Returns a new array containing elements common to the two arrays, with no duplicates. |
2 | array * 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). |
3 | array + other_array Returns a new array built by concatenating the two arrays together to produce a third array. |
4 | array . other_array Returns a new array that is a copy of the original array, removing any items that also appear in other_array. |
5 | str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive. |
6 | array | other_array Returns a new array by joining array with other_array, removing duplicates. |
7 | array << obj Pushes the given object
onto the end of array. This expression returns the array itself, so
several appends may be chained together. |
8 | array <=> other_array Returns an integer (-1, 0, or +1) if this array is less than,
equal to, or greater than other_array. |
9 | array == 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. |
10 | array[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 length elements, 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. |
11 | array[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 length elements, 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. |
12 | array.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. |
13 | array.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. |
14 | array.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. |
15 | array.clear Removes all elements from array. |
16 | array.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. |
17 | array.collect! { |item| block } [or]
array.map! { |item| block } Invokes block once for each element of self, replacing the element with the value returned by block. |
18 | array.compact Returns a copy of self with all nil elements removed. |
19 | array.compact! Removes nil elements from array. Returns nil if no changes were made. |
20 | array.concat(other_array) Appends the elements in other_array to self. |
21 | array.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. |
22 | array.delete_at(index) Deletes the element at the specified index, returning that element, or nil if the index is out of range. |
23 | array.delete_if { |item| block } Deletes every element of self for which block evaluates
to true. |
24 | array.each { |item| block } Calls block once for each element in self, passing that
element as a parameter. |
25 | array.each_index { |index| block } Same as Array#each, but passes the index of the element
instead of the element itself. |
26 | array.empty? Returns true if the self array contains no elements. |
27 | array.eql?(other) Returns true if array and other are the same object, or are both arrays with the same content. |
28 | array.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 an IndexError 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. |
29 | array.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 the absolute index of each element to be filled. |
30 | array.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. |
31 | array.flatten Returns a new array that is a one-dimensional flattening of this array (recursively). |
32 | array.flatten! Flattens array in place. Returns nil if no modifications were made. (array contains no subarrays.) |
33 | array.frozen? Returns true if array is frozen (or temporarily frozen while being sorted). |
34 | array.hash Compute a hash-code for array. Two arrays with the same content will have the same hash code |
35 | array.include?(obj) Returns true if obj is present in self, false otherwise. |
36 | array.index(obj) Returns the index of the first object in self that is == to
obj. Returns nil if no match is found. |
37 | array.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. |
38 | array.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. |
39 | array.insert(index, obj...) Inserts the given values before the element with the given index (which may be negative). |
40 | array.inspect Creates a printable version of array. |
41 | array.join(sep=$,) Returns a string created by converting each element of the array to a string, separated by sep. |
42 | array.last [or] array.last(n) Returns the last element(s) of self. If array is empty, the
first form returns nil. |
43 | array.length Returns the number of elements in self. May be zero. |
44 | array.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. |
45 | array.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. |
46 | array.nitems Returns the number of non-nil elements in self. May be zero. |
47 | array.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 sSiIlL 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 ) |
48 | array.pop Removes the last element from array and returns it, or nil if array is empty. |
49 | array.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. |
50 | array.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. |
51 | array.reject { |item| block } Returns a new array containing the items array for which
the block is not true. |
52 | array.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. |
53 | array.replace(other_array) Replaces the contents of array with the contents of other_array, truncating or expanding if necessary. |
54 | array.reverse Returns a new array containing array's elements in reverse order. |
55 | array.reverse! Reverses array in place. |
56 | array.reverse_each {|item| block } Same as Array#each, but traverses array in reverse order. |
57 | array.rindex(obj) Returns the index of the last object in array == to obj. Returns nil if no match is found. |
58 | array.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. |
59 | array.shift Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty. |
60 | array.size Returns the length of array (number of elements). Alias for length. |
61 | array.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 length elements, 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. |
62 | array.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. |
63 | array.sort [or] array.sort { | a,b | block } Returns a new array created by sorting self. |
64 | array.sort! [or] array.sort! { | a,b | block } Sorts self. |
65 | array.to_a Returns self. If called on a subclass of Array, converts the receiver to an Array object. |
66 | array.to_ary Returns self. |
67 | array.to_s Returns self.join. |
68 | array.transpose Assumes that self is an array of arrays and transposes the rows and columns. |
69 | array.uniq Returns a new array by removing duplicate values in array. |
70 | array.uniq! Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found). |
71 | array.unshift(obj, ...) Prepends objects to the front of array, other elements up
one. |
72 | array.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. |
73 | array.zip(arg, ...) [or]
array.zip(arg, ...){ | arr | block } Converts any arguments to arrays, then merges elements of
array with corresponding elements from each argument. |
months = Hash.new
The collect iterator returns all the elements of a collection. a = [1,2,3,4,5]
b = Array.new
b = a.collect
puts b
a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b
Exception
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end
raise
OR
raise "Error Message"
OR
raise ExceptionType, "Error Message"
OR
raise ExceptionType, "Error Message" condition
|