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
oddball_sum(numbers)
You need a def on the front of the above
i = 0
You need a variable to hold the sum, so
result = 0
while i < numbers.length
if (numbers % 2 !== 0)
you meant numbers[i] % 2 != 0
return numbers[i] += 1
Don’t return here, add this number to the total
result += numbers[i]
i += 1
end
return result
end
But in fact it is better to use each, not a while loop, so something
like
def oddball_sum(numbers)
result = 0
numbers.each { |n| result += n if n %2 != 0 }
return result
end
In fact there are even more concise ways of coding this, but I would
stick with something like the above for the moment in order to keep
the code readable.
I suggest you find some tutorials on Ruby first and work through them,
then when you think you have the basics of Ruby sorted move on to a
good Rails tutorial such as railstutorial.org, which will show you the
basics of Rails.
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
oddball_sum(numbers)
You need a def on the front of the above
i = 0
You need a variable to hold the sum, so
result = 0
while i < numbers.length
if (numbers % 2 !== 0)
you meant numbers[i] % 2 != 0
return numbers[i] += 1
Don’t return here, add this number to the total
result += numbers[i]
i += 1
end
return result
end
But in fact it is better to use each, not a while loop, so something
like
def oddball_sum(numbers)
result = 0
numbers.each { |n| result += n if n %2 != 0 }
return result
end
In fact there are even more concise ways of coding this, but I would
stick with something like the above for the moment in order to keep
the code readable.
I suggest you find some tutorials on Ruby first and work through them,
then when you think you have the basics of Ruby sorted move on to a
good Rails tutorial such as railstutorial.org, which will show you the
basics of Rails.