Skip to main content

Frequently Used Method - Array

Array
1. include?
It will return true if the object passed in match the element in the array. It follows this format, population.include?(sample)
eg: a = [1,2,3]
a.include?(2) 
returns true

2. map / map.with_index  aka.  collect
Iterates through the array , then , create a new array with values returns by the block of code.
Eg: to double all integers in an array
array = [1,2,3]
doubled = array.map { |element| element * 2  }
doubled = [2,4,6]

Another short hand method of writing map is this
Eg: to convert an array of strings into integers.
a = ['2', '3'].map(&:to_i)
a = [2,3]
This will return [2, 3]

It is the same as the method below.
['2', '3'].map { |element| element.to_i }

3. [] = 

It will return the value at index position passed in.
Eg :
a = [1,2,3,4]
a[0] = 1
a[-2] = 3

In OOP, if you want to override this method for your object.
Eg:
def []=(key, value)
end


4. each / each_with_index
Iterate through the array. Returns the original array. The variant with_index creates an index block variable.
a = [1,2,3]
a.each do |x|
   puts x
end
Returns [1,2,3] 
Prints 1, 2, 3

5. flatten
break nested array into one big array.
Eg:
a = [[1,2],[3,4]]
a.flatten 
returns [1,2,3,4]

6. count
count the number of element in an array without argument. With arguments, count the occurrences of the arguments in the array.
Eg;
a = [1,1,2,3]
a.count(1) 
# returns  2
a.count
# returns 4
a.count { |x| x < 2 }
# return 2

7. join
Join an array into a string with or without a specified delimiter
Eg:
a = ["it", "is", "a", "good", "day"]
a.join(" ")
returns "it is a good day"

8. first , last

returns the first and last element in the array respectively.
Eg:
a = [1,2,3,4]
a.first    returns 1
a.last     returns 4

9. push , <<

append the arguments into the array. Mutates the caller.
eg:
a = [1,2,3,4]
a.push(5,6)
a = [1,2,3,4,5,6]

10. select

return an array with elements that evaluates to true in the block.
eg:
a = [1,2,3,4,5]
a.select { |x| x>3 }
returns[4,5]

11. size , length
returns the number of elements in an array
eg:
a = [1,2,3,4]
a.size     
returns 4

12. slice
return a portion of the array.
eg:
a = [1,2,3,4,5]
a.slice(1,2)  returns [2,3]
a.slice(2..3) return [3,4]

13. pop , shift
pop removes the last element of the array, return last element.
shift removes the first element of the array, return first element
both mutate the caller.
eg:
a = [1,2,3,4,5]
a.pop     return 5
a = [1,2,3,4]
a.shift    return 1
a = [2,3,4] 

14. uniq
return a new array with duplicate values removed.
eg:
a = [1,2,3,4,5,5,5]
a.uniq    return [1,2,3,4,5]

15. sample
return a random element in the array
eg:
a = ['a' , 'b', 'c'] 
a.sample    return 'b'  
a.sample    return 'a'

16. sort
return a new array with the element sorted from smallest to largest.
eg:
a= [1,5,2,1,3]
a.sort    return [1,1,2,3,5]

17. reduce , inject
perform the stated operation for all elements in the array
eg :
a = [1,2]
a.reduce(:+)  # return 3
a.inject(:*)    # return 2




Comments

Popular posts from this blog

Problem Solving - Refactored

I am going to outline how I approach problem solving. The relative importance and the amount of effort/time required for each is stated as a percentage beside each topic. I borrowed some idea from George Polya's How to Solve It Thoroughly Understand the Problem (30%) When encountering hard problem , you need to deeply understand the problem at hand. Take a paper and list down all known facts and data and what the question is trying to find. Sketch out the problem if applicable. Visualize the problem in your head. A lot of times, we only have to understand the problem well, then the solution will obvious. Have a Plan (20%) You need to have an outline of how you are going to tackle the problem. You need to have a logical pathway that will ultimate produce outcome (nothing to do with coding syntax yet). Without a plan, you are just randomly poking around and got lucky. No hard problem ever gets solved without a plan. Plan using pseudo-code, pen & paper or flowchart. Use wh...

My Burnout Experience

I want to share with you my experience of burning out. After registering with Launch School, I am extremely excited about my programming journey. I studied for 10 to 12 hours a day, memorizing fact, trying out practice problems, understanding programming concepts. It was fun and exciting and I love seeing myself growing from nothing in programming to something more. After about 3 months, thing starts to change. I started noticing myself paying less attention to details. I find myself skimming through the course material. I skip "Further Exploration" in the practice problem. I am more interested to study just to pass the assessment rather than truly mastering the concept. It was a gradual burning out process but I continue to study for 10 to 12 hours a day through sheer grit. It felt like doing house chore or working a day job that you don't like. One particular morning I woke up, and I remember this deep feeling of dread because I can anticipate that the next 10 to 1...

Explain code

get "/" do pattern = File . join ( data_path , "*" ) @files = Dir . glob ( pattern ) . map do | path | File . basename ( path ) end erb :index end def data_path if ENV [ "RACK_ENV" ] == "test" File . expand_path ( "../test/data" , __FILE__ ) else File . expand_path ( "../data" , __FILE__ ) end end data_path will check if ENV hash with key "RACK_ENV" has the value of "test". If yes, then return the path from root to cms2/test/data folder. If not , then return the absolute path from root to the folder cms2/data Then, in get "/" block , join the data_path with * . If in development environment, then data_path is home/cms2/data then the return value is home/cms2/data/* We use File.join is good because it will detect the OS, then join with appropriate character.  With the pattern in place, we use Dir.glob to find the files. Here it return home/...