Ruby vs Python (WiP)

The ultimate showdown of the programming universe- Ruby vs Python, two interpreted programming languages that offer tons of great features, such as lambdas, syntactical sugar, and functional programming. Both are used for web programming, shell scripts, and desktop applications (and actually more- but lets keep things simple for now). The purpose of this article is to help you as a programmer determine what language is the best fit for you. The code samples are written such that they do the same thing; are similar in design; and compile.

The names in parentheses are the programmers' aliases.

Our first example is a piece of code that determines if a number is small or big depending on a condition. Obviously this is over-complicated, but it makes for an interesting comparison.

Ruby (DT)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def my_if(condition, then_clause, else_clause)
  if condition
    then_clause.call
  else
    else_clause.call
  end
end

5.times do |n|
  my_if n < 2,
        -> { puts "#{n} is small" },
        -> { puts "#{n} is big" }
end


Python (LF)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def my_if(condition, then_clause, else_clause):
  if condition:
    then_clause()
  else:
    else_clause()

for n in range(5):
  my_if (n < 2,
    lambda : print("{0} is small".format(n)),
    lambda : print("{0} is big".format(n))
  )

Ever need to randomly shuffle lines? Maybe for a playlist, or to decide what you're eating throughout the day or at a restaurant? Well, here's some code that does just that. I must admit Ruby has an elegant one-liner here. It is very clear though what is going on in the Python version.

Ruby (AP)

1
STDIN.read.split("\n").shuffle.each { |line| puts line }


Python (LF)

1
2
3
4
5
6
import sys
from random import shuffle
lines = sys.stdin.readlines()
shuffle(lines)
for line in lines:
  print(line)

Python could have had a one-liner if the shuffle() function returned the list. Unfortunately it returns None, but if it had returned the new list, we could've done:

1
print(str.join('', shuffle(sys.stdin.readlines())))

It is interesting to note that Python reads from in-to-out, whereas Ruby reads from left-to-right when it comes to one-liners.

Comments

Popular Posts