1

This, will be a very strange question. And I really doubt it is possible. Some will call this stupid, and I wouldn't agree more. But it is for mere curiosity!

class MyClass
  def initialize
    print "Ha"
  end
end

Is there a way to print the class file? I mean, create a .txt file, containing exactly the code above?

Saturn
  • 17,888
  • 49
  • 145
  • 271

1 Answers1

3

Sure. You can use the magic constant __FILE__ which contains the path to the file that you use it in:

class MyClass
  def initialize
    puts File.read(__FILE__)
  end
end

This will print the contents of the file containing the definition of MyClass every time you create a MyClass object.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • I see! Thanks. Is there any other way, thought? – Saturn Jan 17 '11 at 23:59
  • @Omega: Sure, you could also do `File.open(__FILE__) do |f| f.read end` or ``cat #{__FILE__}` instead of `File.read(__FILE__)`. But there's no way without using `__FILE__` and some way of reading a file from the file system. – sepp2k Jan 18 '11 at 00:01
  • @sepp2k: It is indeed possible to print a ruby program from a ruby program without using `__FILE__` and without reading from file system. See http://stackoverflow.com/questions/2474861/shortest-ruby-quine for some examples. – Don Roby Jan 18 '11 at 00:17
  • @Don: If that's what the OP meant, I completely misunderstood the question (thinking about it I probably did). I thought he wanted to print the source code of the class as a means of reflection. A quine of course requires you to already know the contents of the file. – sepp2k Jan 18 '11 at 00:21
  • @sepp2k: Since he accepted your answer, I doubt you misunderstood too badly! – Don Roby Jan 18 '11 at 00:26