From: Chris White Date: 2011-08-10T07:18:10+09:00 Subject: Re: Inspect method > I don't know if Amir got it, but I certainly don't. After throwing a few 'irb' lines I still don't understand where should I use inspect of each. > > "Time.new.inspect == puts x = Time.new" > > Which as you said makes sense, because turns the obj into string, but can you explain a bit the list example? > > I have the same problem with .map which is often used by many developers… > > I don't understand the difference between map and each. I find them to have the same results. I'm not sure why inspect is being referenced with map and each. However I'll first address inspect: irb(main):008:0> x = "#{[1,2,3]}" => "[1, 2, 3]" irb(main):009:0> x.eql? [1,2,3].inspect => true irb(main):010:0> [1,2,3].inspect => "[1, 2, 3]" The string interpolation of the array [1,2,3] calls to_s behind the scenes, producing a string representation of the array. If we check this against the output of the same array with the inspect method called on it, notice how the string is equal. This is because inspect is also calling to_s of the array, as shown by the final irb output. However, if we have an object that overrides both to_s and inspect: class MyObj attr_reader :name, :age def initialize(name, age) @name = name @age = age end def to_s "#{@name} #{@age}" end def inspect "[MyObj] name: #{@name} age: #{@age}" end end Now I'll load this file in an irb session: irb(main):001:0> load 'class.rb' => true irb(main):002:0> obj = MyObj.new("John", 200) => [MyObj] name: John age: 200 irb(main):003:0> "#{obj}" => "John 200" irb(main):004:0> "#{obj}".eql? obj.inspect => false irb(main):005:0> The result is now false because I've overridden the inspect method to produce a custom result different from to_s. This is what I meant by "it depends. Now to answer you question about map or each, it's important to check the result: irb(main):003:0> [1,2,3].each { | x | x * x } => [1, 2, 3] irb(main):004:0> [1,2,3].map { | x | x * x } => [1, 4, 9] Inside the block, the actions are the same. the element is multiplied by itself. However each still has the original array while map returns a new array with the result of the modification of each element, or more specifically the result of each iteration of the block: irb(main):005:0> [1,2,3].map { | x | "a" } => ["a", "a", "a"] Since "a" is the return of the block, all array elements are set to "a", totally disregarding the original value. Map can also be used to modify the original array by using the "!" suffixed version: irb(main):006:0> x = [1,2,3] => [1, 2, 3] irb(main):007:0> x.map! { | x | x * x } => [1, 4, 9] irb(main):008:0> x => [1, 4, 9] In this case the original value of x is lost and replaced with an array that contains the results of the block called on each element. Does that make sense? Regards, Chris White http://www.twitter.com/cwgem