ruby API problem

Question 1

Let's create a method that outputs the sum of any three numbers. However, if the same number is included It does not count towards the total.

Output example:

lone_sum([1, 2, 3]) → 6 lone_sum([3, 2, 3]) → 2 lone_sum([3, 3, 3]) → 0

The question this time was a difficult and completely misguided answer! I wasn't sure that the arguments were arrays. However, when an array appears as a tendency, each statement feels like an iron plate.

Below is the answer.

def lone_sum(ary)
  #Extract only unique elements from the array
  uniq_nums = []
  ary.each do |num|
    count = 0
    ary.each do |i|
      if num == i
        count += 1
    if count < 2
      uniq_nums << num

  # uniq_Total in nums array
  sum = 0
  uniq_nums.each do |unique_num|
    sum += unique_num

  puts sum


For example, consider calling a method with lone_sum ([3, 2, 3]). ① ary = [3,2,3] ②ary.each do |num|Then, take out the contents of the array one by one. ③ The first number taken out is 3, so num = 3. ④ The second each statement, ary.each do |i|Then i= 3,2,It becomes 3. ⑤ When the conditional expression if num (3 is taken out) == i, that is, when they are duplicated, the count increases. (6) Add a value to the uniq_nums array only when there is one duplicate value in the 11th line. When num = 3, count = 2, so no value is added to the uniq_nums array. ⑦ As a result of repeating this two more times, only 2 is added to the uniq_nums array. ⑧ The sum in the uniq_nums array is written with sum = 0 or less. ⑨ In this case, sum = sum + 2, that is, sum = 0 + 2. Finally the total is output as 2.


I understand, but how long will it take to reach a level where this can be solved in the future? If anyone knows what kind of study method can be used to get closer to the correct answer, please let me know. For the time being, all I can do is study.

Recommended Posts

ruby API problem
[Ruby] Ruby API problem
ruby API problem
Ruby problem ⑦
ruby search problem
[Ruby] FizzBuzz problem
[Ruby] FizzBuzz problem
Use Face API from Ruby
[Ruby] problem with if statement
Ruby deposit system, algorithm problem
Calendar creation problem (fun Ruby practice problem)
[Ruby] Search problem using index method
This problem is soberly difficult ... (Ruby)
Ruby learning 4
I tried a calendar problem in Ruby
[N + 1 problem]
Rails API
Call API [Call]
Ruby basics
Ruby learning 5
Ruby basics
Ruby Review 2
Ruby addition
Refactoring Ruby
Ruby learning 3
FizzBuzz problem
Ruby setting 2
Ruby learning 2
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
Ruby settings 1
Refactoring Ruby
Ruby basics
Ruby memo
Ruby learning 1
[Problem] Weather on consecutive holidays (Ruby edition)
Ruby Review 1
[Ruby] Module
Procedure for operating google spreadsheet with API (ruby)
[Competition Pro] Solve the knapsack problem with Ruby
Try to get redmine API key with ruby