Ruby on Rails Tuesday, August 4, 2015

When I looked at your code sample, I immediately thought that I should look at the Ruby Integer, Emumerable  and Array API.  I reviewed them....
On review of the Ruby Integer API revealed the method .odd?
On review of the Ruby Array API revealed the methods .select
On review of the Ruby Enumerable API revealed the methods .reduce

So I built the solution, but from what I learned that are many possibilities, and admittedly this solutions may not be the best or the fastest

my_odd_ball_sum =  numbers.select {|n| n.odd?}.reduce(:+)

Breakdown...

numbers.select
select { |item| block } → new_ary
select → Enumerator

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


numbers.select {|n| n.odd?}  returns an Enumerator, so then apply reduce(:+)

reduce(sym) → obj

Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.


My point is that it is a good idea/investment to explore Ruby API for solutions.
Hope this helps
Liz


On Monday, August 3, 2015 at 10:57:08 PM UTC-4, Ruby-Forum.com User wrote:
Hi,

I am new to Ruby on Rails.  I am practicing problems to better
understand coding.  I understand the logic but I am not able to put in
proper codes.  Could someone please solve the following problem for me?

oddball_sum
Write a function oddball_sum(numbers), which takes in an array of
integers and returns the sum of all the odd elements.

oddball_sum(numbers)
i = 0
while i < numbers.length
if (numbers % 2 !== 0)
return numbers[i] += 1
i += 1
end
return result
end

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/87da231f-6a96-4814-909d-5b39a47827df%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment