From: Joel Wilsson Date: 2001-08-25T10:43:49+09:00 Subject: [ruby-talk:20342] Re: Backwards language Hi Sean, > Perhaps you have some good examples that'd sway my opinion I'm currently writing an ftpd in Ruby, and I've been experimenting with a few language features (lots of fun :) I've found that eval is one of the most interesting functions there is. Here's a snippet (ab)using it. ftpmethods = [ ] @socket.methods.each { |m| if (m =~ /^ftp_/) and not (m =~ /reply\d+/) ftpmethods << m.sub(/^ftp_/, "") end } big_case = "case s\n" ftpmethods.each { |m| big_case += "when /^#{f}/i\n @socket.ftp_#{f} s.sub(/^#{f} */i, \"\")\n" } big_case += "else @socket.ftp_reply502 unless @socket.closed? end" until socket.closed? s = @socket.gets unless socket.closed? eval big_case end @socket has been extended by an FTP command module, which has functions like ftp_user, ftp_pass, ftp_stor, and an FTP reply module which has functions like ftp_replyXXX where XXX is a three-digit reply code (specified by the FTP RFC). First I loop over @socket's method and add "user", "pass" etc., and big_case checks the FTP clients reply string to see if it matches any of the FTP methods supported by @socket. Instead of having to type out all FTP methods manually, the wonderful loop takes care of all that. As an extra bonus I only have to add FTP commands to the FTP command module and have them work automatically, without having to add them to the "big case". Oh, and the FTP reply module is also created by an eval, which takes a hash of the form "CODE" => "description" and makes a module out of it. For example: # some replies need arguments, which are aN "215" => "#{a0} system type." # Creates the method (in the FTP reply module) ftp_reply215 (a0) puts "#{a0} system type.\r\n" # this is so i can use commands like # "ftp_reply501 and return unless setup_ok?" # all reply functions return true return true end No, the code isn't exactly easy to read, and can get quite confusing, but I'm not trying to write readable code, I'm trying to have fun with Ruby (and I AM having lots of fun :) While these examples may be a bit extreme, I hope you see how extremely powerful eval() really is. It's when you go wild with language features you realize how unique Ruby is. Regards, Joel Wilsson