[英]Return the lines which have no given symbol in Ruby
I want to print the lines from a website's content page which do not start with the symbol "#"
. 我想从网站的内容页面打印不以符号
"#"
开头的行。
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
Expected result: 预期结果:
2d75cc1bf8e57872781f9cd04a529256
00f538c3d410822e241486ca061a57ee
3f066dd1f1da052248aed5abc4a0c6a1
781770fda3bd3236d0ab8274577dddde
................................
It works when I try to print the lines that start with "#"
: 当我尝试打印以
"#"
开头的行时,它将起作用:
lines[0] != "#"
But it does not work in the opposite way. 但这并非相反。
You could just use a mix of reject
and start_with?
您可以混合使用
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?('#') }
It outputs : 输出:
2d75cc1bf8e57872781f9cd04a529256
00f538c3d410822e241486ca061a57ee
3f066dd1f1da052248aed5abc4a0c6a1
781770fda3bd3236d0ab8274577dddde
86b6c59aa48a69e16d3313d982791398
42914d6d213a20a2684064be5c80ffa9
10699ac57f1cf851ae144ebce42fa587
248338632580f9c018c4d8f8d9c6c408
999eb1840c209aa70a84c5cf64909e5f
12c4201fe1db96a1a1711790b52a3cf9
................................
If you just want the first line : 如果只想第一行:
page_content.each_line.find{ |line| !line.start_with?('#') }
page_content.each_line do |lines|
lines
should be called line
. lines
应该称为line
。 It is just one line. 这只是一行。
When you call 你打电话时
lines.each_line do |line|
You iterate over "each" line of just one line, so the loop isn't needed at all. 您只需遍历一行的“每一”行,因此根本不需要循环。
Your code could be : 您的代码可能是:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.