'Trying to create a function to sum odd integers
Trying to get this program to ask for numbers and then add the odd integers. Looking to link the prompt with the function.
puts("give me numbers")
gets = numbers
def oddball_sum(numbers)
i = 0
while i < numbers.length
if (numbers[i]%2!=0)
result += numbers[i]
i+=1
end
return result
end
end
Solution 1:[1]
What I would do:
puts("give me numbers")
gets # read user input: `"1,2,3,4 5"`
.scan(/\d+/) # extract numbers from input: `["1", "2", "3", "4", "5"]`
.map(&:to_i) # translate numbers to integers: `[1, 2, 3, 4, 5]`
.select(&:odd?) # select all odd values: `[1, 3, 5]`
.sum # sum the remaining values in the array: `9`
# give me numbers
# input: 1,2,3,4 5
# => 9
Solution 2:[2]
Here are some examples to sum a list of odd integers: First the minimal changes to get your code working.
puts("give me numbers")
numbers = gets.split.map {_1.to_i}
def oddball_sum(numbers)
result = 0
i = 0
while i < numbers.length
if (numbers[i]%2!=0)
result += numbers[i]
end
i+=1
end
return result
end
puts oddball_sum(numbers)
- You had gets and numbers swapped, you want to get the string and save it in numbers.
- You need to split the string based on some separator. You did not answer @spickermann's question so I assumed spaces.
- You need to define result outside the
ifstatement - You need to move the
return resultto after the loop completes
Then two more versions
puts("give me numbers")
numbers = gets.split.map { _1.to_i }
odd_numbers = numbers.select { _1.odd? }
sum_of_odds = odd_numbers.sum
puts sum_of_odds
puts("give me numbers")
sum_of_odds = gets # get a line from the terminal
.split # split the line based on spaces, this creates an array of strings
.map { _1.to_i } # map each string value to an interger value
.select { _1.odd? } # filter the array to only the odd values
.sum # sum up the remaining values
puts sum_of_odds
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | spickermann |
| Solution 2 |
