Okay, I don’t have a lot of time here. We’re on a tight schedule. But hey tests are running so I’ll write a tiny bit of Crystal.
How would I print a quick summary of a file? Besides ls
, of course. I mean how would I print a quick summary of a file using Crystal?
We already looked at Crystal as a glue language. No, I’m wondering more about how I would get this information using Crystal’s standard library.
Turns out I can get the same information with File::Info
.
This is both more and less information than I was hoping for. Clearly whoever wrote to_s
for File::Info
figured the main time you would need to directly print the object is when you were debugging. That makes sense, and they provide methods to get at the information I care about most.
I grabbed the logic from weighing-files-with-python to get a description of the size in kilobytes, megabytes, or gigabytes. That is easier for my brain to understand than the UInt64
integer byte count provided by File::Info.size
.
Yes, the whole thing is more clever than the situation requires, but I am trying to learn the language here. Using a Proc
was one way to basically copy and paste the logic from my earlier post and reformat for Crystal. Sure, I could have — and probably should have — defined a new, separate method. At the same time, Procs are great to show that there’s this bit of behavior you want to encapsulate, but you don’t plan to use anywhere else.
But really it was just a bit of late night silliness so I could see Crystal Procs in action. Silliness for the sake of learning is okay.
And what did I learn?
File::Info
gives me what I want for file summaries.- Crystal supports Tuples: special immutable lists that can be more efficient than a full
Array
String.build
is a nice-looking way to make multiline strings without heredocs or+=
. Apparently there are performance reasons to use it too, but I’ll never see them in this short program. Same with Tuples really, but the type you specify can tell people what your intentions are.Proc
argument types must be specified. That must mean the compiler treats them differently than normal methods.
Hang on. I’m curious to explore that last one. Procs are treated differently. Are they faster?
The method is almost three whole nanoseconds faster than the Proc. I wonder…
Yeah, that’s what I thought. For this case at least, local environment variations — did Spotify just hit a new track? — will have a bigger impact than whether I choose a Proc or a method.
Okay, tests are done. Everything passed, yay! Back to it. Maybe back to the drawing, actually.
Backlinks
Got a comment? A question? More of a comment than a question?
Talk to me about this page on: mastodon
Added to vault 2024-01-15. Updated on 2024-02-02