Ruby array is a list of elements that can be of any type either string or integer. Hence, In ruby it can be integer or string.
we can declare array by placing the elements inside the brackets like;-
arr = [1,"array",2,3,"hello",6.5]
you can see the above declared array has string, integer and float. In ruby array can have any data type inside them.
now lets focus on how to fetch the value of array, if you want to fetch the first value of array then we can do like this
arr.first
if you want to fetch the value by indexing
arr[3] /* it will fetch the value of array on index no. 3 */
How to Modify existing Array
Once we declare array we can also modify its elements, we can do that in 2 ways.
- push
- pop
push is used to add extra element inside the array.
arr.push("new string")
pop is used to remove last element from an array.
arr.pop
it will remove last element from the array.
HASHES IN RUBY
Ruby hashes are the data structure in which we store items by keys, entries in hash are stored in a key value pair where keys are created as symbol and value is created as data type.
a = {:hello => 'welcome to ruby'}
this is the older syntax of hash in ruby.
Now a days we usually use newer syntax:
new_syntax ={ hello: 'welcome to ruby' }
you can have multiple of key value pairs inside one hash.
a = { id: '1' , roll: '2' , address: 'delhi' }
if you want to add new key value pair to existing hash you can do like this
a[:office] = 'Gurgaon'
it will add new element inside a { a hash } with :office as a key and 'Gurgaon' as value.
How to delete a element from Hash
you can also delete an element from an existing hash
a.delete(:id)
it will delete id from existing {hash a }
0 Comment(s)