开发者

puts matches from to files

I have mac addresses in mac1.txt and mac2.txt and I wanted to do something like this:

v = File.open("/RubyDev/sort/mac1.txt",'r').each_line do |a|
      w = File.open(开发者_Python百科"/RubyDev/sort/mac2.txt",'r').each_line do |b|
            if w in v
                puts w
            end
      end
end

Thanks in advance for your assistance!


EDIT: That first version below is actually pretty terrible. Here's a better version:

lines = []

File.open("mac1.txt",'r').each_line do |a|
  lines.push(a.rstrip!)
end

File.open("mac2.txt",'r').each_line do |b|
  if lines.include?(b.rstrip!)
    puts b
  end
end

I think what you're looking for is something like this:

File.open("mac1.txt",'r').each_line do |a|
  File.open("mac2.txt",'r').each_line do |b|
    if a == b
      puts b
    end
  end
end

Is that correct? If not, could you give more background about the issue and what you're trying to accomplish?


To get all the common lines between two files, you can use File#readlines to access all the lines in the file as an array. Keep in mind that they will still have newlines ("\n") appended, so you'll need to remove them with String#chomp. The easiest way to do this is to map the array that readlines gives you, like this:

common_macs = File.open("mac1.txt").readlines.map(&:chomp) & 
  File.open("mac2.txt").readlines.map(&:chomp)


I am still trying to learn Ruby, so this is unlikely a good solution, but it is a possibility. It reads the contents of the first file into a hash and then checks the contents of the second against it. I think it would be reasonably efficient (well ... unless the first file is too big to fit nicely in memory).

lines = Hash.new

File.open( "mac1.txt", 'r' ).each_line do |l|
    lines[l] = true
end

File.open( "mac2.txt", 'r' ).each_line do |l|
    if ( lines[l] == true )
        puts l
    end
end

Edit For completeness, here is the very succinct version as suggested in the comments by Mark Thomas with the white space removal suggested by Gavin Anderegg. Ruby is a sweet language.

lines = Hash.new
File.open( "mac1.txt", 'r' ).each_line {|l| lines[l.strip!] = true}
File.open( "mac2.txt", 'r' ).each_line {|l| puts l if lines[l.strip!]}


lines = {}
File.open("mac1.txt").each_line {|l| lines[l.chomp] = true}
File.open("mac2.txt").each_line {|l| puts l if lines[l.chomp]}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜