arrays - 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
解决方案
看起来您的销售总额方法仅适用于一个条目,而不是我认为您想要的列表。修复它看起来像:
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
!
推荐阅读
- slack-api - 处理用户交互 - 单击按钮消息不像记录的那样
- laravel - Laravel 排序和限制左连接的结果
- sql-server - 有没有办法在使用 LinqPad 连接到 MSSQL 时指定 SPN
- git - Windows 中 Git 中的权限克隆失败
- c++ - 为什么需要在朋友功能中提及对象?
- reactjs - Monaco Editor 0.20 不响应元素大小变化(没有窗口大小变化)
- python - Pyspark:基于具有许多条件的列表过滤数据帧
- python - 如何将列表中的所有单词和短语放入搜索表达式(Python)
- swiftui - swiftui - 将视图保存到变量
- petapoco - 具有 Sql 层次结构 ID 的 DNN MVC 模块