Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

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

Other Data Structures

Although web apps are ultimately about strings, actually making those strings requires using other data structures as well. In this section, we’ll learn about some Ruby data structures important for writing Rails applications.

Arrays and Ranges

An array is just a list of elements in a particular order. We haven’t discussed arrays yet in the Rails Tutorial, but understanding them gives a good foundation for understanding hashes (Section 4.3.3) and for aspects of Rails data modeling (such as the has_many association seen in Section 2.3.3 and covered more in Section 10.1.3).

         So far we’ve spent a lot of time understanding strings, and there’s a natural way to get from strings to arrays using the split method:

>> "foo bar    baz"  split               # Split a string into a three-element array
=> ["foo",  "bar",   "baz"]

The result of this operation is an array of three strings. By default, split divides a string into an array by splitting on whitespace, but you can split on nearly anything else as well:  

>> "fooxbarxbazx" .split   ('x')
=> ["foo",  "bar",  "baz"]

As is conventional in most computer languages, Ruby arrays are zero-offset, which  means that the first element in the array has index 0, the second has index 1, and so on: 

We see here that Ruby uses square brackets to access array elements. In addition to this bracket notation, Ruby offers synonyms for some commonly accessed elements:6

>> a                            # Just a reminder of what 'a' is
=> [42, 8, 17]
>> a.first
=> 42
>> a.second
=> 8
>> a.last

 

=> 17
>> a.last == a   [-1]    [-1]               # Comparison using ==
=> true 

 

This last line introduces the equality comparison operator ==, which Ruby shares with many other languages, along with the associated != (‘‘not equal’’), etc.: 

>> x = a.length                             # Like strings, arrays respond to the 'length' method.
=> 3
>> x  == 3
=> true
>> x  == 1
=> false
>> x   != 1
=> true
>> x   >= 1
=> true
>> x   < 1
=> false
 

 In addition to length (seen in the first line above), arrays respond to a wealth of other methods:

 

>> a
=> [42,  8,  17]
>> a.sort
=> [8,  17,  42]
>> a.reverse
=> [17,  8,  42]
>> a.shuffle
=> [17,  42,  8]
>> a
=> [42, 8, 17]
 
 
 
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)