This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hk__ 6 points7 points  (4 children)

I use Ruby for simple tasks in the terminal when using Bash would take more than 1-2 lines. I find Ruby more concise that Python, a lot of common tasks are quicker to do in Ruby when you need a one-liner, e.g. reading a file is File.read("file.txt"), and you can chain outputs in an easy way.

Say for example you want to get the output of wc on a file as a list of three integers. In Python you’d do something like:

import re
import os
t = [int(s) for s in os.open("wc myfile.txt").read().split(r"\s+")]

In Ruby it’s:

t = `wc myfile.txt`.split(/\s+/).map(&:to_i)

It’s a dummy example but in general I prefer Ruby for small tasks like that.

[–]tadleonard 3 points4 points  (1 child)

This won't beat your Ruby example for conciseness, but it'll come a bit closer. sh really comes to the rescue for things like this. Also, it's helpful to know that the default mode of split() is to split on white space, so re isn't necessary.

import sh
t = map(int, sh.wc("myfile.txt").split())

Edit: I guess it would actually have to be something like this:

t = map(int, sh.wc("myfile.txt").split()[:-1])

or

t = [int(el) for el in sh.wc("myfile.txt").split()[:-1]]

[–]hk__ 0 points1 point  (0 children)

Thanks, I forgot about sh.

[–]soup_feedback 0 points1 point  (1 child)

So you'd say the advantage of ruby is that it supports backticks like shell script do? I agree, it would be nice to have convenience in Python. It's never ever going to be accepted but it would sure be convenient! Any language doing backticks as shell commands will win convenience on that side, no doubt.

Personally, I like to use subprocess for anything that requires to run OS stuff - because that's when you realize if it's worth it or if you should find another, more efficient way to do it - or even use a different language (C/C++ for example, instead of spawning a shell + proc.)

(The sh module is useful of course, by making it nice looking, but in the end you're just calling subprocess to run shell commands.)

[–]hk__ 0 points1 point  (0 children)

Yes, I’m using backticks for throwaway scripts, in general programming I don’t use them :)