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

 

Advertisements

Debugging Methods

Here are few methods that we can use for debugging:

1) Kernal#Caller

 caller.inspect

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)
m.class
=> Method
m.call
=> "HELLO WORLD"

3) source_location

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

Dog.new.method(:bark).source_location

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

4) ancestors

"foo".class.ancestors
=> [String, Comparable, Object, Kernal, BasicObject]

In class method you can simply call it like:

self.class.ancestors

5) Module#method_defined?

"foo".class.method_defined?(:upcase)
=> true
99.class.method_defined?(:upcase)
=> false

6) Method#instance_method

Instead of

User.new.method(:github_url).source_location

you can use:

User.instance_method(:github_url).source_location

.

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
reconstituted.
Rails uses marshaling to store session data.