by area51org · 3y ago · 0 comments
This:
dirp = Dir.open(".")
for f in dirp
case f
when /\.rb\z/
print f, "\n"
else
# do not print
end
end
dirp.close
Could be made much more Ruby-native (and simpler!) as: Dir.open('.').each do |f|
puts f if f.match?(/\.rb\z/)
end
My point isn't to play the "I know the language better than you, so nyah nyah" game, just to suggest that if the author likes Ruby as much as he says, he should learn it better.That pretty not great ruby wasn't written by the author -- it's actually included in a "sample" file with the ruby distro?
https://github.com/ruby/ruby/blob/ruby_3_1/sample/dir.rb
A file whose commit history shows... it's part of the very first commit recorded in git history, in 1998 by matz, the original author of ruby.
I have no idea what's going on in that "sample" folder, very weird.
The OP is simply regurgitating the weird "sample" folder. The "author" of the OP didn't write any of this code. According to git history... matz did?!?
In any case, I wonder if the OP's motives were good or if this was just some SEO game... we have enough of the latter on the internet.
So not necessarily written by Matz, but part of the body of work that eventually saw a `git init`, and early enough that much of the modern standard Ruby formatting was still emerging. Doesn't seem all that surprising to me in the context of when it was written.
$ curl -s https://cache.ruby-lang.org/pub/ruby/1.0/ruby-0.49.tar.gz | tar -tvz | grep dir.rb
-rw-r--r-- 0 matz root 127 Jun 3 1994 ruby/sample/dir.rb dirp = Dir.open(".")
dirp.rewind
for f in dirp
if (~/^\./ || ~/~$/ || ~/\.o/)
else
print(f, "\n")
end
end
dirp.close[0] https://github.com/ruby/ruby/commit/3db12e8b236ac8f88db8eb46...
puts Dir["*.rb"]Not really Python like at all - apart from the one line with for. Python doesn't have a case or when statement, or syntax level regex, doesn't open or close directories, and for files it would idiomatically would use the context manager for file access rather than closing it.
But it also doesn't look like any Ruby I've seen or written either :)
I just finished a class that was taught with Ruby. It seems like an absolutely delightful language, but I could not find docs pertaining to several projects that I had conceptualized as my 'final project'. Microsoft Graph API has no docs available for Ruby.
Dir.open('.') do |dirp|
dirp.each do |f|
puts f if f.match?(/\.rb\z/)
end
end
https://ruby-doc.org/core-3.1.0/Dir.html#method-c-openThere are a few ruby stdlib classes like Tempfile that use the finalizer trick you mention to free resources on GC but Dir isn’t one of them. Here’s it’s implementation:
https://github.com/ruby/ruby/blob/1a24442193fe437e761e941d1a...