返回Ruby中没有给定符号的行

时间:2017-03-22 08:58:43

标签: ruby string readline

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

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] != "#"

但它不会以相反的方式起作用。

1 个答案:

答案 0 :(得分:2)

您可以混合使用rejectstart_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