方法Array#*
采用整数:
thumbs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
thumbs = thumbs*2
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如何将数组乘以任何浮点数而不仅仅是整数?例如,我希望得到以下结果:
thumbs = thumbs*1.5
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
答案 0 :(得分:4)
array = [*1..10]
fraction = 1.5
thumbs = array.cycle.take((array.length * fraction).floor)
根据您希望处理小数案例的方式,您可以使用ceil
或round
代替floor
。
答案 1 :(得分:1)
只是因为Array * x
仅被定义为使用整数。
因为在某些情况下,不清楚从中得到什么输出。例如
[1,2,3]*1.5
这应输出[1,2]
还是[1]
?
您可以定义自己的方法:
class Array
alias_method :old_mult , :'*' # remember, how old multiplication worked
def * other # override * method
result = old_mult(other.floor) # multiply with floored factor
end_index = (size * (other % 1)).round # convert decimal points to array index
result + self[0...end_index] # add elements corresponding to decimal points
end
end
p [1,2] * 1
p [1,2,3] * 2
p [1,2,3,4,5] * 1.5
p [1,2,3,4,5,6] * 1.5
此输出
[1, 2]
[1, 2, 3, 1, 2, 3]
[1, 2, 3, 4, 5, 1, 2, 3]
[1, 2, 3, 4, 5, 6, 1, 2, 3]
答案 2 :(得分:0)
您可以定义方法并执行任何操作:
def arr_times(f, arr)
i = float.to_i
arr*i + arr[0..(((f-i)*arr.length).floor)]
end