15 Most Useful Methods Of Array In Ruby
Anuraag Misshra
Top 1% on Topmate | Ruby on Rails | React JS | Web | API | Mentoring young professionals to advance their career in Ruby on Rails from average to exceptional by using the ProX framework
As a Ruby on Rails developer, mastering the array methods provided by Ruby not only enhances your code efficiency but, also deepens your understanding of this elegant programming language.?
In this article, I will walk you through some of the most essential and powerful Ruby array methods, providing practical examples to help you grasp their applications in real-world scenarios.
Initialization
a = Array.new # []
b = Array.new(3) # [nil, nil, nil]
c =Array.new(3, true) # [true, true, true]
Standard Iteration and Transformation Methods
[1, 2, 3].each { |num| puts num }
# 1
# 2
# 3
2. each_with_index: Similar to each, but also passes the index of the elements.
["a", "b", "c"].each_with_index { |item, index| puts "#{index}: #{item}" }
# 0: a
# 1: b
# 2: c
3. map: Returns a new array containing the values returned by the block.
squares = [1, 2, 3].map { |num| num * num }
puts squares # [1, 4, 9]
4. map! (destructive): Modifies the original array instead of creating a new one.
numbers = [1, 2, 3]
numbers.map! { |num| num * num }
puts numbers # [1, 4, 9]
Filtering and Selection Methods
5. select and reject: Return new arrays based on the block’s truth value. select returns an array containing all elements of the enum for which the given block returns a true value, whereas reject returns an array for all the elements of the enum for which the given block returns false or nil.
even = [1, 2, 3, 4].select { |num| num.even? }
odd = [1, 2, 3, 4].reject { |num| num.even? }
puts even # [2, 4]
puts odd # [1, 3]
6. delete_if and keep_if (destructive): Modify the array by deleting elements. delete_if removes the element for which the block returns true, while keep_if does the opposite.
numbers = [1, 2, 3, 4, 5]
numbers.delete_if { |num| num > 3 }
puts numbers # [1, 2, 3]
numbers = [1, 2, 3, 4, 5]
numbers.keep_if { |num| num > 3 }
puts numbers # [4, 5]
Advanced Manipulation Methods
7. flatten: Flattens nested arrays into a single-dimensional array.
领英推荐
nested = [1, [2, 3], [4, 5]]
flat = nested.flatten
puts flat # [1, 2, 3, 4, 5]
8. compact: Removes nil elements from the array.
array_with_nils = [1, nil, 3, nil, 5]
compact_array = array_with_nils.compact
puts compact_array # [1, 3, 5]
9. uniq: Removes duplicate elements from the array.
duplicates = [1, 2, 2, 3, 3, 3, 4]
unique_elements = duplicates.uniq
puts unique_elements # [1, 2, 3, 4]
10. push, pop: Methods to add or remove elements from the ends of the array.
stack = []
stack.push(1) # [1]
stack.push(2) # [1, 2]
last = stack.pop # [1], 2 returned
11. shift, unshift: Methods to add or remove elements from the front of the array.
queue = []
queue.unshift(1) # [1]
queue.unshift(2) # [2, 1]
first = queue.shift # [1], 2 returned
Specialized Methods
12. combination: Yields all combinations of length n of array elements.
[1, 2, 3].combination(2) { |c| p c }
# [1, 2]
# [1, 3]
# [2, 3]
13. fetch: Tries to return the element at the position index, throwing an exception if the index is out of range unless a default is given.
numbers = [1, 2, 3]
puts numbers.fetch(1) # 2
puts numbers.fetch(4, "N/A") # "N/A"
14. max: Returns the largest value.
puts [1, 2, 3, 4, 5].max # 5
15. reverse: Returns a new array containing the items in reverse order.
puts [1, 2, 3].reverse # [3, 2, 1]
Conclusion
Ruby arrays offer a rich set of methods that cater to almost every need one might encounter in daily programming tasks.?
Familiarizing yourself with these methods can dramatically increase your productivity and help you write more elegant and efficient Ruby code.
?Whether you’re preparing for a job interview or just refining your programming skills, these array methods are indispensable tools in your Ruby toolkit.
Software Developer?? at Taskcraft Technology | Ruby?? | Proficient in ?Ruby on Rails(RoR)?| StimulusJs | Rspecs | JavaScript | PostgreSQL | GIT | Docker ?? | #ruby #rubyonrails #ror #ROR #Rails #webdevelopment
10 个月Thanks for sharing