如何解决将参数作为参数传递给方法时,如何忽略数组中的其他元素? 红宝石
我最初尝试做的是在给定数组中找到元素的相应索引并将它们连接起来。我的代码是
class ResistorColorDuo
COLORS = %w{black brown red orange yellow green blue violet grey white}
def self.value(colors_arry)
colors_arry.map { |color| COLORS.index(color) }.join.to_i
end
end
puts ResistorColorDuo.value(["brown","orange"])
puts ResistorColorDuo.value(["black","brown"])
puts ResistorColorDuo.value(["orange","brown","red"])
puts ResistorColorDuo.value(["orange","red","yellow"])
#13
#1
#312
#3124
查找和连接它们似乎没有问题,但真正的目标是仅从前两个元素获取结果,而忽略后面的元素。例如,通过["orange","yellow"]
时,我应该得到31
而不是3124
。我有什么办法吗?
谢谢。
解决方法
只包含.first(2)也会删除.to_i,如果它在开头,它将删除0:
class ResistorColorDuo
COLORS = %w{black brown red orange yellow green blue violet grey white}
def self.value(colors_arry)
colors_arry.first(2).map { |color| COLORS.index(color) }.join
end
end
puts ResistorColorDuo.value(["brown","orange"])
puts ResistorColorDuo.value(["black","brown"])
puts ResistorColorDuo.value(["orange","brown","red"])
puts ResistorColorDuo.value(["orange","red","yellow"])
输出将是:
13
01
31
31
,
如果将输出转换为Integer,则0索引将排在最前面。
class ResistorColorDuo
COLORS = %w{black brown red orange yellow green blue violet grey white}
def self.value(colors_arry)
colors_arry.map { |color| COLORS.index(color) }.join.chars.shift(2).join
end
end
p ResistorColorDuo.value(["brown","orange"])
p ResistorColorDuo.value(["black","brown"])
p ResistorColorDuo.value(["orange","red"])
p ResistorColorDuo.value(["orange","yellow"])
输出
"13"
"01"
"31"
"31"
,
您可以通过Array#[]
从数组中提取前2个元素:
ary = ["orange","red"]
ary[0,2] #=> ["orange","brown"]
0
是起始索引,2
是元素数。
我注意到您正在使用单类方法来计算电阻器的值。由于Ruby都是关于对象的,因此使用 instances 并将value
转换为实例方法似乎是合理的。这种方法还可以对计算进行一点划分,例如:
class Resistor
COLORS = %i[black brown red orange yellow green blue violet grey white].freeze
attr_accessor :color_bands
def initialize(*color_bands)
@color_bands = color_bands
end
def digits
color_bands[0,2].map { |color| COLORS.index(color) }
end
def value
digits.join.to_i
end
end
Resistor.new(:brown,:orange).value #=> 13
Resistor.new(:black,:brown).value #=> 1
在使用3或4个色带时,可以通过将乘数作为单独的方法添加进来,以将其考虑在内:
class Resistor
# ...
def multiplier
case color_bands.size
when 1,2 then 1
when 3,4 then 10 ** COLORS.index(color_bands[2])
end
end
def value
digits.join.to_i * multiplier
end
end
Resistor.new(:orange,:brown,:red).value #=> 3100
在上面的代码中,我还将字符串更改为符号,并使用了splat运算符*
,因此您可以简单地传递颜色列表。 (无需将它们包装在数组中)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。