Search code examples
rubyjruby

Print only unique array elements to file in Ruby


I am trying to write the output to a file. But when I write this code, it is writing the same line multiple times. How can i stop repeating the same line multiple times?

Java_location is my output.

Here is my code:

a = []
a << java_location
File.open("/home/weblogic/javafoundmodified.txt", 'w+') do |file|
  a.each { |item| file.puts item }
end

My output i am getting now is:

1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.7.0_72/u01/java/jdk1.7.0_72/jre/bin/java
1.7.0_72/u01/java/jdk1.7.0_72/jre/bin/java
1.7.0_72/u01/java/jdk1.7.0_72/jre/bin/java
1.7.0_72/u01/java/jdk1.7.0_72/bin/java
1.7.0_72/u01/java/jdk1.7.0_72/bin/java
1.7.0_72/u01/java/jdk1.7.0_72/bin/java
1.7.0_65/u01/java/jdk1.7.0_65/jre/bin/java
1.7.0_65/u01/java/jdk1.7.0_65/jre/bin/java
1.7.0_65/u01/java/jdk1.7.0_65/jre/bin/java

Solution

  • Consider this (with example array in javalocation):

    javalocation = %w|
    1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
    1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
    1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
    1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
    1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
    1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
    1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
    1.7.0_72/u01/java/jdk1.7.0_72/jre/bin/java
    1.7.0_72/u01/java/jdk1.7.0_72/jre/bin/java
    1.7.0_72/u01/java/jdk1.7.0_72/jre/bin/java
    1.7.0_72/u01/java/jdk1.7.0_72/bin/java
    1.7.0_72/u01/java/jdk1.7.0_72/bin/java
    1.7.0_72/u01/java/jdk1.7.0_72/bin/java
    1.7.0_65/u01/java/jdk1.7.0_65/jre/bin/java
    1.7.0_65/u01/java/jdk1.7.0_65/jre/bin/java
    1.7.0_65/u01/java/jdk1.7.0_65/jre/bin/java
    |
    
    File.open("/home/weblogic/javafoundmodified.txt", 'w+') do |file|
      javalocation.uniq.each { |line| file.puts line }
    end