Arrays
Extract of interesting topics about arrays.
Creation
Array literals
| %i | symbols - create an array of symbols |
| %w | strings - create an array of strings |
%i( symbol1 symbol2 symbol3 ) # => [ :symbol1, :symbol2, :symbol3 ]
%i{ symbol1 symbol2 symbol3 } # => [ :symbol1, :symbol2, :symbol3 ]
%w( string1 string2 string3 ) # => [ "string1", "string2", "string3" ]
%w{ s1 s2 s3 s4\ with\ blanks } # => [ "s1", "s2", "s3", "s4 with blanks" ]
Predicates
any?
[].any? # => false
[ false, nil ].any? # => false
[ false, nil, true ].any? # => true
[ false, nil, 0 ].any? # => true
[].any? { |e| e >= 3 } # => false
[ 1, 2 ].any? { |e| e >= 3 } # => false
[ 1, 2, 3 ].any? { |e| e >= 3 } # => true
all?
[].all? # => true
[ false, true ].all? # => false
[ nil, true ].all? # => false
[ true, 0, 'nil', :false, 0.000 ].all? # => true
[].all? { |e| e >= 3 } # => true
[ 1, 2 ].all? { |e| e >= 3 } # => false
[ 2, 3, 4 ].all? { |e| e >= 3 } # => false
[ 3, 4, 5 ].all? { |e| e >= 3 } # => true
include?
empty?
Filtering
Filter to keep - positive filtering
filter{ |element| <boolean expression> }
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter { |e| e.odd? } # => [1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter( &:odd? ) # => [1, 3, 5, 7, 9]
Filter to eliminate (to get rid of) - negative filtering
reject{ |element| <boolean expression> }
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reject { |e| e.even? } # => [1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reject( &:even? ) # => [1, 3, 5, 7, 9]