Bala
Bala

Reputation: 11264

Why "select" does not return true value or is it?

[1,2,5,8,3].collect{|i| i.to_s} #=> ["1", "2", "5", "8", "3"]

Whereas

[1,2,5,8,3].select{|i| i.to_s} #=> [1, 2, 5, 8, 3]

As per ruby-doc select => "Returns a new array containing all elements of ary for which the given block returns a true value."

Isn't the true value here should be i.to_s value

Upvotes: 1

Views: 548

Answers (3)

lacrosse
lacrosse

Reputation: 54

You can think of #collect as a map operation and #select as a filter, hence #select's return value is always a subset of the initial array.

Upvotes: 0

bjhaid
bjhaid

Reputation: 9762

In ruby anything order than nil or false is true

So:

[1,2,5,8,3].select{|i| i.to_s} is equivalent to [1,2,5,8,3].select{|i| true }

which would both evaluate to:

[1,2,5,8,3].select{|i| i.to_s} #=> [1, 2, 5, 8, 3]
[1,2,5,8,3].select{|i| true } #=> [1, 2, 5, 8, 3]

as you said in the question

select => "Returns a new array containing all elements of ary for which the given block returns a true value.

So select would return the original array since the block always evaluates to true.

However collect

Returns a new array with the results of running block once for every element in enum.

So:

[1,2,5,8,3].collect{|i| i.to_s} #=> ["1", "2", "5", "8", "3"]
[1,2,5,8,3].collect{|i| true } #=> [true, true, true, true, true]

Upvotes: 2

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

Because #select the only selects the values from the array, when block is evaluated to non-false, and returns the new array:

{|i| i.to_s } # => false|nil or non-false|nil

while #collect generates the new array by appying block to each of current array values:

{|i| i.to_s } # => i.to_s => "String"

Upvotes: 1

Related Questions