Different ways of Iterating over an Array in Ruby (Just for me)

1) .each do |val| … end

2) .each_with_index do |val, index| … end

3) a) .map do … end  => returns new array

b) .map.with_index do |val, index| … end

4) .any? do |val| {condition} end   => returns true or false

5) .all? do |val| {condition} end   => returns true if all value satisfy the condition otherwise false

6) .select do |val| {condition} end   => returns an array of those values which satisfy condition.

7) .find do |val| {condition} end   => returns first value which passes condition.

8) .find_all do |val| {condition} end   => returns all those value which satisfy conditon. It’s equivalent to .select

9) .inject([initial_value_of_var1]) do |var1, var2 | … end => returns var1


Debugging Methods

Here are few methods that we can use for debugging:

1) Kernal#Caller


shows you where you have been.

It will give you “file:line in method”

2) Method

It is a class.

m = "Hello World".method(:upcase)
=> Method

3) source_location

It will give address and line number. It shows you where you are going.


It will give you address with line number of this above(:bark) method.

4) ancestors

=> [String, Comparable, Object, Kernal, BasicObject]

In class method you can simply call it like:


5) Module#method_defined?

=> true
=> false

6) Method#instance_method

Instead of


you can use:



here we don’t need to create instance.

Marshaling Objects

Ruby can take an object and convert it into a stream of bytes that can be
stored outside the application. This process is called marshaling.
This saved object can later be read by another instance of the application (or by a totally
separate application), and a copy of the originally saved object can be
Rails uses marshaling to store session data.