Skip to content

Instantly share code, notes, and snippets.

@Quemia
Last active April 6, 2020 06:01
Show Gist options
  • Select an option

  • Save Quemia/6e8a30d7f507194023f2626adfaf20d0 to your computer and use it in GitHub Desktop.

Select an option

Save Quemia/6e8a30d7f507194023f2626adfaf20d0 to your computer and use it in GitHub Desktop.

Array in Ruby

It is a list of items in order (like mangoes, apples and oranges). Each position in the list acts as a variable: you can see which object a particular position points to and can make it point to some object.

ex:

 #array empty and  array index starts at 0
 var1 = [] 
 puts var1 [0] 

 

 # stores two strings
 var2 = ['hello', 'bye'] 
 puts var2 [0]
 puts var2 [1]

 flavor = mang
 #array whose elements point to three objects: float, sting and array.
 var4 = [80.5, flavor, [true, false]] 
 puts var4 [2]

  linguas.each do | lang |
    puts 'I love' + lang + '!'
    puts 'aren't you?'
  end
=>
     "I love English!"
     "not you?"
     "I love French!"
     "not you?"
     "I love Casteliano!"
     "not you?"
     => ['English', 'Frances', 'Casteliano']

Some methods of the array class

    

 newarr = [45, 23, 1, 90]

     #organizes the order of the array. p newarr.sort => [1, 23, 45, 90]


 #gives the size of the array.
 p newarr.leght 
 => 4

 #shows the first array position.
 p newarr.first 
 => 45

 #shows the last position of the array.
 p newarr.last 
 => 90
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment