我正在做一个简单的彩票游戏。目前它从txt文件中获取序列号和彩票号码,并将它们放在一个二维数组中。
现在我想要一个检查等级,如果有任何重复的序列号和彩票号
example:
5153,177 = 1
54338,115 = 1
74522,171 = 3
我尝试过制作一个支票号码方法,它不会给出任何错误,但是当我这样做时
puts sold.checkgrade
它不起作用
我怎么能在我的例子中做到这一点?
class Lottery
attr_accessor :lotnumber
attr_accessor :serialnumber
def initialize(lotnumber, serialnumber)
@lotnumber = lotnumber
@serialnumber = serialnumber
end
def checknumber
ObjectSpace.each_object(Lottery).to_a.select do |other|
@lotnumber == other.lotnumber && @serialnumber == other.serialnumber
end.size
end
end
my txt
29371,43
13797,6
8114,55
70657,106
32741,74
7272,103
37416,14
5153,177
54338,115
74522,171
74522,171
74522,171
答案 0 :(得分:0)
这是一个完整的工作示例,只是更改了名称。
尝试运行此代码,然后修改名称以匹配您的项目。
class Counter
attr_accessor :a
attr_accessor :b
def initialize(a, b)
@a, @b = a, b
end
def check_duplicates
ObjectSpace.each_object(self.class).to_a.select do |other|
@a == other.a && @b == other.b
end.size
end
end
two_match = Counter.new(1, 2) # 2 Matches
duplicate = Counter.new(1, 2)
no_match = Counter.new(1, 1) # 1 Match
puts two_match.check_duplicates
# => 2
puts no_match.check_duplicates
# => 1
答案 1 :(得分:0)
Ruby的group_by
方法是一个很好的起点:
data = %w[
29371,43
13797,6
8114,55
70657,106
32741,74
7272,103
37416,14
5153,177
54338,115
74522,171
74522,171
74522,171
]
data.group_by{ |s| s }.map{ |k, v| [k, v.size] }
# => [["29371,43", 1],
# ["13797,6", 1],
# ["8114,55", 1],
# ["70657,106", 1],
# ["32741,74", 1],
# ["7272,103", 1],
# ["37416,14", 1],
# ["5153,177", 1],
# ["54338,115", 1],
# ["74522,171", 3]]
内在的魔力是,group_by
创建一个数组哈希:
data.group_by{ |s| s }
# => {"29371,43"=>["29371,43"],
# "13797,6"=>["13797,6"],
# "8114,55"=>["8114,55"],
# "70657,106"=>["70657,106"],
# "32741,74"=>["32741,74"],
# "7272,103"=>["7272,103"],
# "37416,14"=>["37416,14"],
# "5153,177"=>["5153,177"],
# "54338,115"=>["54338,115"],
# "74522,171"=>["74522,171", "74522,171", "74522,171"]}
如果你想要一个哈希而不是一个数组数组:
Hash[data.group_by{ |s| s }.map{ |k, v| [k, v.size] }]
# => {"29371,43"=>1,
# "13797,6"=>1,
# "8114,55"=>1,
# "70657,106"=>1,
# "32741,74"=>1,
# "7272,103"=>1,
# "37416,14"=>1,
# "5153,177"=>1,
# "54338,115"=>1,
# "74522,171"=>3}