On Tue, Oct 15, 2013 at 6:25 PM, Joel P. [email protected]
wrote:
The simplest way to extract the matching values would be to use
Array#select, which retains all the elements where the block evaluates
truthfully.
def array_copy(source)
source.select { |val| val < 4 }
end
Right, but I guess that task was about something else.
Ruby’s syntax allows for some single-line conditionals, including these
constructs:
method if condition
method unless condition
Actually it’s “expression” instead of “method”. You can even do
irb(main):001:0> 1 if 2 > 3
=> nil
irb(main):002:0> 1 if 2 < 3
=> 1
If you wanted to have an else in a single-line condition, the simplest
way would be to use the ternary operator:
condition ? true_method : false_method
Maybe it’s worthwhile to mention that if then else is actually an
expression (actually everything is in Ruby) and not a statement as in
some other programming languages. You can even fit it “nicely” on a
single line:
irb(main):009:0> if 1 > 0; ‘a’ else ‘b’ end
=> “a”
irb(main):010:0> if 1 < 0; ‘a’ else ‘b’ end
=> “b”
But I agree: the ternary operator is much more elegant.
On Tue, Oct 15, 2013 at 6:26 PM, Joel P. [email protected]
wrote:
John M. wrote in post #1124612:
My first question is why are we iterating over source not array_copy
which is the method containing all the source?
The destination Array at first is an empty Array. Iterating over it
would result in 0 iterations.
Since John asked about iterating “array_copy” I’d like to add:
array_copy is actually the name of the method - it’s not an Array or
other collection of values like “source” is. So you cannot iterate
“array_copy”. And as Joel explained to copy something from a to b you
need to go through a - and nothing else.
Kind regards
robert