On 4 August 2015 at 03:56, Dhaval Bhatt <lists@ruby-forum.com> 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)
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.
Colin
--
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/CAL%3D0gLt3p4Tdy70jA%2BCFPTv%2BmR9WkPDcJz8SgbhAH3_Dd%2B%3D_VA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment