Home > Software engineering >  Trying to create a function to sum odd integers
Trying to create a function to sum odd integers

Time:02-21

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 

CodePudding user response:

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

CodePudding user response:

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)
  1. You had gets and numbers swapped, you want to get the string and save it in numbers.
  2. You need to split the string based on some separator. You did not answer @spickermann's question so I assumed spaces.
  3. You need to define result outside the if statement
  4. You need to move the return result to 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
  •  Tags:  
  • ruby
  • Related