Re:Ruby: A great language for shell scripts
by cyclotron3k on Sunday June 23, 2024 @04:29AM
(#40765710)
Personally, I find Ruby's syntax more natural, (I'm going to be heavily biased though, having written Ruby for 10+ years). But for example, let's say I wanted to make a hash (dict) of files, keyed by their size (for some unknown reason), in Ruby it would look like:
Whereas the equivalent Python would be:
Or capitalizing a string in Ruby:
And in Python:
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.
[ Parent
| on HN ]
You can capitalize a string in Python using functional style
' '.join(map(str.capitalize, string.split(' ')))
which is similar to the example in Ruby, except the operations are written in reverse order.
Re:Ruby: A great language for shell scripts
by pseudalopex on Sunday June 23, 2024 @08:57AM
(#40767146)
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()
Re:Ruby: A great language for shell scripts
by sgarland on Sunday June 23, 2024 @09:15AM
(#40767254)
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) }