gpt4 book ai didi

Ruby:将方法合并为 1 行

转载 作者:行者123 更新时间:2023-12-02 02:49:55 25 4
gpt4 key购买 nike

我有一个对象数组,我想采用其中一种方法将其返回到单行中。

这是我的数组

def set
@seconds = Counter.new('Seconds')
@minutes = Counter.new('Minutes')
@hours = Counter.new('Hours')

@time = [@seconds, @minutes, @hours]
end

这是我尝试在 Counter 类中打印的方法

    def count
@counts
end

这是我的尝试

    def read
reverse = @time.reverse
@time.each do |t|
return '%02d' %t.count.to_s.join(":")
end
end

(我还希望它们采用 00、01 格式,因此是“%02d”)

.join 似乎不起作用(我猜它适用于数组,但不适用于数组的方法?

任何帮助将不胜感激!

最佳答案

鉴于此 Counter 类和一些实例:

class Counter
attr_accessor :count

def initialize(name, count: 0)
@name = name
@count = count
end
end

@seconds = Counter.new('Seconds', count: 52)
@minutes = Counter.new('Minutes', count: 30)
@hours = Counter.new('Hours', count: 11)

@time = [@seconds, @minutes, @hours]

您可以通过以下方式提取按小时/分钟/秒顺序排列的计数值:

@time.reverse.map(&:count)
#=> [11, 30, 52]

该数组可以(全​​部)传递给 String#%生成 HH:MM:SS 字符串:

'%02d:%02d:%02d' % @time.reverse.map(&:count)
#=> "11:30:52"

一些改进

您可以通过更改 @time 数组的顺序来摆脱 reverse:

@time = [@hours, @minutes, @seconds]

'%02d:%02d:%02d' % @time.map(&:count)
#=> "11:30:52"

这可以通过提供 to_i 方法进一步简化:

class Counter
# ...

def to_i
@count
end
end

# ...

@time = [@hours, @minutes, @seconds]

'%02d:%02d:%02d' % @time
#=> "11:30:52"

上面的代码之所以有效,是因为 % 在指定整数格式时尝试调用 to_i

关于Ruby:将方法合并为 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62164399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com