Insert into Ruby Array
The following piece of code insert to each hash in the array a new element. I used destructive hash merge to add the new element to each hash in the array.
The following piece of code insert to each hash in the array a new element. I used destructive hash merge to add the new element to each hash in the array.
You can process every element in Ruby array using a loop or you may use ruby Array map or collect (Map and Collect are different names for same function). The Second and fourth print statements in the next example will print [2, 3, 4, 5, 6]. The functions that end with ! will modify the original array itself since it is destructive. The first and third will print the array [1, 2, 3, 4, 5] since the method map or collect did not change the array itself (it did not end with !)
1) Ruby Array is collection of objects that do not need to be the same type. That means, ruby array class can hold Fixnum, float, string, etc objects in the same array. The following peace of code:
Will return
Fixnum
Float
String
Array
=> [1, 1.2, "2", [1, 2, 4]]
2) Ruby arrays can be concatenated using + sign, for example
arr3 will be [1, 2, 3, 4]
3) Ruby array is quite circular. Ruby Array allows reverse index; negative index.
The previous peace of code going to return 6 which is located at index = -1.
4) Ruby Array has the following methods
& * + - << <=> == [] [] []= abbrev assoc at clear collect collect! compact compact! concat dclone delete delete_at delete_if each each_index empty? eql? fetch fill first flatten flatten! frozen? hash include? index indexes indices initialize_copy insert inspect join last length map map! new nitems pack pop pretty_print pretty_print_cycle push quote rassoc reject reject! replace reverse reverse! reverse_each rindex select shift size slice slice! sort sort! to_a to_ary to_s to_yaml transpose uniq uniq! unshift values_at yaml_initialize zip |