Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2|
Lessons:- Other Data Structures

Note that none of the methods above changes a itself. To mutate the array, use the corresponding ‘‘bang’’ methods (so-called because the exclamation point is usually
pronounced ‘‘bang’’ in this context):

>>  a
=>  [42,  8,  17]

 

>>  a.sort!
=> [8,  17,  42]
>>  a
=>  [8,  17,  42] 

You can also add to arrays with the push method or its equivalent operator, <<: 

>> a.push   (6)                           # Pushing 6 onto an array
=> [42,  8 , 17,  6]
>> a << 7                               # Pushing 7 onto an array
=> [42,  8,  17,  6,  7]
>> a << "foo" << "bar                  # Chaining array pushes
=> [42,  8,  17,  6 , 7,  "foo",  "bar"]

 

This last example shows that you can chain pushes together and also that, unlike arrays in many other languages, Ruby arrays can contain a mixture of different types (in this case, integers and strings). Before we saw split convert a string to an array. We can also go the other way with the join method:  

>> a
=> [42,  8,  17,  7,  "foo",  "bar"]
>> a.join                                                                  # Join on nothing
=>  "428177foobar"
>> a.join(', ')                                                        # Join on comma-space
=> "42, 8, 17, 7, foo, bar"

Closely related to arrays are ranges, which can probably most easily be understood by converting them to arrays using the to_a method:

 

>> 0..9
=>  0..9
>> 0..9. to a                                                                # Oops, call to a on 9
NoMethodError: undefined method `to a' for 9:Fixnum
>>  (0..9). to  a                                                              # Use parentheses to call to a on the range
=>  [0,  1,  2,  3,  4,  5,  6,  7,  8,  9]

Although 0..9 is a valid range, the second expression above shows that we need to add parentheses to call a method on it. 

              Ranges are useful for pulling out array elements:

>> a = %w[foo  bar  baz  quux]                      # Use %w to make a string array.
=> ["foo",  "bar",  "baz",  "quux"]
>> a   [0..2]
=> ["foo",  "bar",  "baz"]

Ranges also work with characters:

>>  ('a'..'e').to a
=>  ["a",  "b",  "c",  "d",  "e"] 

 

 
 
 
image
Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student
Explore
 

  Students (0)