Here's is an array with 5 elements 2.1.2 :001 > arr = ["a", "b", "c", "d", "e"] => ["a", "b", "c", "d", "e"] Lets look at few different cases Insert a new element at starting position Using unshift 2.1.2 :002 > arr.unshift("f") => ["f", "a", "b", "c", "d", "e"] Using insert 2.1.2 :005 > arr.insert(0, "f") => ["f", "a", "b", "c", "d", "e"] In the above example 0 is the position(index) Move existing element from one position to another The element in this case is "e" Using uniq to show only unique elements 2.1.2 :009 > arr.insert(0, "e").uniq => ["e", "a", "b", "c", "d"] With uniq we are only showing unique records but the element is listed
In JavaScript, you may combine the indexOf() method and the filter() method to get rid of duplicates from an array function removeDuplicates(arr) { return arr.filter((el, index) => arr.indexOf(el) === index); } let numbers = [1, 2, 3, 3, 4, 4, 5]; let uniqueNumbers = removeDuplicates(numbers); console.log(uniqueNumbers); // [1, 2, 3, 4, 5] The removeDuplicates() function in this code accepts an array as an argument and produces a new array that is empty of duplicates. This is accomplished by creating a new array with the filter() method that only contains elements that are unique within the original array. A callback function is provided as an argument to the filter() method, which is used to filter each element of the array. By comparing the current element's index to the output of executing indexOf() on the original array, the callback function determines if the current element exists only once in the array. The element is added to the new array if the two indices a
Validations allow you to ensure that only valid data is stored in your database. Example: validates_presence_of :user_name, :password validates_numericality_of :value We can write custom validation also as def validate errors.add(:price, “should be a positive value”) if price.nil?|| price < 0.01 end Callbacks and observers allow you to trigger logic before or after an alteration of an object’s state. Callbacks are methods that get called at certain moments of an object’s life cycle. With callbacks it’s possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database. Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attribu
Comments
Post a Comment