gpt4 book ai didi

ruby - 可以使用 ruby​​ 触发器作为过滤器不那么笨拙吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:06:09 26 4
gpt4 key购买 nike

为了获取部分文本,我在触发器前面使用了 true if kludge:

desired_portion_lines = text.each_line.find_all do |line|
true if line =~ /start_regex/ .. line =~ /finish_regex/
end
desired_portion = desired_portion_lines.join

如果我删除 true if 位,它会提示

bad value for range (ArgumentError)

有没有可能让它不那么笨拙,还是我应该这样做

desired_portion_lines = ""
text.each_line do |line|
desired_portion_lines << line if line =~ /start_regex/ .. line =~ /finish_regex/
end

或者是否有更好的不使用枚举的方法?

最佳答案

如果你一行一行地做,我的偏好是这样的

line =~ /finish_regex/ && p=0
line =~ /start_regex/ && p=1
puts line if p

如果你把所有的都放在一个字符串中。我会使用拆分

mystring.split(/finish_regex/).each do |item|
if item[/start_regex/]
puts item.split(/start_regex/)[-1]
end
end

关于ruby - 可以使用 ruby​​ 触发器作为过滤器不那么笨拙吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5061174/

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