Tuesday, 31 March 2015

Ruby all? method, Wow nice


As the name indicates returns a boolean value either true or false.
Takes a block as a argument if block is not supplied takes the default block({ |item| item }) as argument.

The source of all? says that it stores the result of iteration in the static variable and then perform the AND operation from the result of next iteration.

Lets do some logical with all?

[123,456,789].all?
=>true

[123,456,789].all?{|b| b > 100 }
=>true


[123,456,nil].all?
=>false

[123,456,789].all?{|b| b > 200 }
=> false

it will return true when all the array elements satisfies the condition written in block evaluates to true.

8 comments:

  1. [].all?
    => true

    How is "all?" method on empty array/list returning "true"?

    ReplyDelete
    Replies
    1. When the block is omitted, all? uses this implied block: {|item| item}.

      Since everything in Ruby evaluates to true except for false and nil, using all? without a block on an array is effectively a test to see if all the items in the collection evaluate to true (or conversely, if there are any false or nil values in the array).

      Using all? without a block on a hash is meaningless, as it will always return true.

      Delete
    2. -all? : The method returns true if the block never returns false or nil.

      -any? : The method returns true if the block returns a value other than false or nil.

      irb(main):004:0> [nil, "car", "bus"].all?
      => false
      irb(main):005:0> ["nil", "car", "bus"].all?
      => true
      irb(main):006:0> [].all?
      => true
      irb(main):007:0> ["nil", "car", "bus"].any?
      => true
      irb(main):008:0> [nil, "car", "bus"].any?
      => true
      irb(main):009:0> [nil].any?
      => false
      irb(main):010:0> [].any?
      => false

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hi @selvaganapathy,

    As I mentioned, the source of all? says that it stores the result of iteration in the static variable (which is set to true initially ) and then perform the AND operation from the result of next iteration. as because of empty collection the block will never get executed and the all method return the static variable declared which was set to true.

    ReplyDelete
    Replies
    1. I've understood the process after reading this text "the static variable declared which was set to true". Thank you.

      Delete