by lr4444lr · 2y ago · 0 comments
Pathname.glob('*').filter { |f| f.file? }.each_with_object({}) { |f, h| h[f.size] = f }
Whereas the equivalent Python would be: result = {}
for file_path in glob.glob('*'):
if os.path.isfile(file_path):
result[os.path.getsize(file_path)] = file_path
Or capitalizing a string in Ruby: string.split(' ').map(&:capitalize).join(' ')
And in Python: words = string.split(' ')
capitalized_words = [word.capitalize() for word in words]
result = ' '.join(capitalized_words)
Python seems to be more convoluted and verbose to me, and requires more explicit variable declarations too. With the Ruby you can literally read left to right and know what it does, but with the Python, I find I have to jump about a bit to grok what's going on. But maybe that's just my lack of Python experience showing. result = {os.path.getsize(f): f for f in os.listdir() if os.path.isfile(f)}
result = ' '.join(word.capitalize() for word in string.split(' '))
result = ' '.join(map(str.capitalize, string.split(' ')))
result = string.title() ' '.join(map(str.capitalize, string.split(' ')))
which is similar to the example in Ruby, except the operations are written in reverse order. from string import capwords
result = capwords(string)
This does the split/capitalize/join dance, all in one.The file example you gave could also be turned into a dict comprehension if desired. I’m on mobile, but I think this would work.
result = { f:os.path.getsize(f) for f in glob.glob(“*”) if os.path.isfile(f) } $ irb
irb(main):001:0> def foo(x=70) = x
=> :foo
irb(main):002:0> i = 2
=> 2
irb(main):003:0> foo / 5/i
=> 7
irb(main):004:0> foo /5/i
=> /5/i`foo + bar` and `foo+bar` are `foo()+bar`, but `foo +bar` is `foo(+bar)`
ternary ? : also has some interesting whitespace dependent mixups with symbols, but I cannot remember what. I think that parser has many gotchas like that, but they are really really rare to bite you, because ruby's magic follows human intuition as much as possible.