首页 > 解决方案 > This is a ruby file , I would like to ask why my junior sales cannot adding to other?

问题描述

class SalesAgent
  attr_accessor :sname, :stype, :samount

  def initialize (name, type, amount)
    #complete initialize() function
    @sname = name
    @stype = type
    @samount = amount
  end
end

def main

  # create a new array
  sale = Array.new
  # repeat the following all the 4 sales agents
  input = "Yes"
  while input == "Yes"||input == "yes"
  puts "Input agent name:"
  # get input from user
  sname = gets.chomp
  
  puts "Input agent type (Junior/Senior):"
  # get input from user
  stype = gets.chomp

  
  puts "Input sales made by this agent (RM):"
  # get input from user (float type)
  samount = gets.chomp.to_f
  sales = SalesAgent.new(sname, stype, samount)
  sale << sales
  juniorsum(sales)
  puts "Key-in another agent data ? (Yes/No)"
  input = gets.chomp
  end
  # create the new SalesAgent object from the input above
  # add the new SalesAgent object into the array
  # call display() function
  sale.each {|sales| display(sales)}
  # call juniorsum() function
  juniorsum(sales)
  # print total sales made by all the junior sales agents
  sleep(1)
  puts "Total sales made by junior is RM " + juniorsum(sales).to_s
end

# This function receives an array as parameter
def display(sales)
  puts "Name: #{sales.sname}"
  puts "Sales: #{sales.samount.to_s}"
  puts ""
  #display names of all the sales agents and their individual sales amount 
end

# This function receives an array as parameter 
# It calculates and returns the total sales made by all the junior sales agents
def juniorsum(sales)
  if sales.stype =="Junior"||sales.stype == "junior"
  total = total = sales.samount
  end
  return total  
end
main

标签: arraysruby

解决方案


看起来您的销售总额方法仅适用于一个条目,而不是我认为您想要的列表。修复它看起来像:

def juniorsum(sales)
  sales.select do |s|
    s.stype.downcase == 'junior'
  end.inject(0) do |sum, s|
    sum + s.samount
  end
end

用于select查找所有“初级”销售的地方,然后inject总结samount价值。这种过滤减少模式很常见,因此无论何时遇到此类问题都值得研究和使用。

请注意调用它,您需要传入数组,而不是单个条目:

puts "Total sales made by junior is RM #{juniorsum(sale)}"

请注意,您调用该方法两次,一次无缘无故。如果要在字符串中进行插值,请使用#{...}插值方法。不需要to_s


推荐阅读