【问题标题】:Return the lines which have no given symbol in Ruby返回 Ruby 中没有给定符号的行
【发布时间】:2017-03-22 08:58:42
【问题描述】:

我想打印网站内容页面中不以符号 "#" 开头的行。

def open(url)
  Net::HTTP.get(URI.parse(url))
end

page_content = open('https://virusshare.com/hashes/VirusShare_00000.md5')

line_num=0
page_content.each_line do |lines|
  line_num += 1
  if lines[0] == "#"
    lines.each_line do |line|
      if (line_num==1)
        puts line
      end
    end
  end
end

预期结果:

2d75cc1bf8e57872781f9cd04a529256
00f538c3d410822e241486ca061a57ee
3f066dd1f1da052248aed5abc4a0c6a1
781770fda3bd3236d0ab8274577dddde
................................

当我尝试打印以"#" 开头的行时它可以工作:

lines[0] != "#"

但反之则不行。

【问题讨论】:

  • 包含还是开始?试试if lines.include? "#"
  • 已编辑,谢谢。它以@WiktorStribiżew 开头
  • @WiktorStribiżew 我更喜欢开始的 :)

标签: ruby string readline


【解决方案1】:

您可以混合使用 reject 和 start_with? :

require 'net/http'
def open(url)
  Net::HTTP.get(URI.parse(url))
end

page_content = open('https://virusshare.com/hashes/VirusShare_00000.md5')

puts page_content.each_line.reject{ |line| line.start_with?('#') }

它输出:

2d75cc1bf8e57872781f9cd04a529256
00f538c3d410822e241486ca061a57ee
3f066dd1f1da052248aed5abc4a0c6a1
781770fda3bd3236d0ab8274577dddde
86b6c59aa48a69e16d3313d982791398
42914d6d213a20a2684064be5c80ffa9
10699ac57f1cf851ae144ebce42fa587
248338632580f9c018c4d8f8d9c6c408
999eb1840c209aa70a84c5cf64909e5f
12c4201fe1db96a1a1711790b52a3cf9
................................

如果你只想要第一行:

page_content.each_line.find{ |line| !line.start_with?('#') }

注意事项

page_content.each_line do |lines|

lines 应称为line。就一行。

当你打电话时

lines.each_line do |line|

您只遍历一行的“每一”行,因此根本不需要循环。

您的代码可能是:

require 'net/http'

def open(url)
  Net::HTTP.get(URI.parse(url))
end

page_content = open('https://virusshare.com/hashes/VirusShare_00000.md5')

page_content.each_line do |line|
  puts line if line[0] != "#"
end

【讨论】:

  • 非常感谢,但我还有一个问题。我怎样才能把该行的第一行不以“#”开头?。我现在正在使用数组,但这不是一个体面的方法。能给个提示吗?
  • 我只想用这条线“2d75cc1bf8e57872781f9cd04a529256”。这是输出的第一行。
猜你喜欢
  • 1970-01-01
  • 2013-10-29
  • 2011-06-29
  • 2013-09-30
  • 2010-09-11
  • 1970-01-01
  • 2012-10-12
  • 2012-08-07
  • 2018-03-21
相关资源
最近更新 更多