Search code examples
rubyreturnargv

Return the for-loops and print txt file


I am trying a code, that will open a file when the for - loops method will generate letters and when this letters will be join together and form 'abcd' this will return the script and print the txt file. I have tried different possibilities but for the moment only have been able to stop the script and to print all the time letters, also printed the file. But never have been able to make all working together.

def words(target)
  filename = ARGV.first

 txt = open(filename)

  ('a'..'z').each do |i|
    ('a'..'z').each do |j|
      ('a'..'z').each do |h|
        ('a'..'z').each do |g|

   together = i+j+h+g
   print together

case together
 when together == target
  return print txt.read

           end
         end
       end
     end
   end
 end

words("abcd")

Thanks in advance.


Solution

  • This is not how case works, you should use if instead:

    def words(target)
      filename = ARGV.first
    
     txt = open(filename)
    
      ('a'..'z').each do |i|
        ('a'..'z').each do |j|
          ('a'..'z').each do |h|
            ('a'..'z').each do |g|
              together = i+j+h+g
              print together
    
              if together == target
                return print txt.read
              end
            end
          end
        end
      end
    end
    
    words("abcd")
    

    Or, if you insist on using case (for some reason):

    case together
      when target
        return print txt.read
    end