Ismail Moghul
Ismail Moghul

Reputation: 2984

making a hash.to_file method

I have the following method...

class output 
  # Converts a hash into a file file.
  def to_file(hash, output)
    output_file = File.new(output, 'w')
    hash.each do |id, seq|
      output_file.puts id
      output_file.puts sequence
    end
    output_file.close
  end
end

So when I need to write the contents of a hash into a file, so I would write the following:

to_output = output.new 
to_output.to_file(hash_name, output_file_name)

This is what I would like to do...

hash_name.to_file(output_file_name)

Is this possible and would this be better since I wouldn't need instantiate the 'output' class...

Upvotes: 0

Views: 66

Answers (1)

falsetru
falsetru

Reputation: 369054

Define Hash#to_file:

class Hash 
  def to_file(output)
    output_file = File.new(output, 'w')
    each do |id, seq|
      output_file.puts id
      output_file.puts seq
    end
    output_file.close
  end
end

Changes:

  • class output => class Hash
  • The parameter hash is gone.
  • hash.each became each (or self.each)
  • Fixed a typo: sequence => seq

Upvotes: 2

Related Questions