Computer Science Canada [Python-tut] Conversions of Ruby-tut code |
Author: | wtd [ Sat Jun 26, 2004 12:16 am ] | ||||||||||||||||||
Post subject: | [Python-tut] Conversions of Ruby-tut code | ||||||||||||||||||
The first post here will be a conversion of the code from my "Hello, Ruby!" tutorial. I'll be sticking with the most basic version, since Python lacks a lot of the "nifty" features Ruby has in abundance. Of course, in all fairness, it also has a lot of nifty tricks Ruby lacks. In Ruby
In Python
In Ruby
In Python
Compare and Contrast Python's "print" statement is roughly equivalent to Ruby's "puts" method, but adds an extra newline to any string. It should also be noted that "print" in Python is a language construct, while "puts" and "print" in Ruby are merely methods which can be dealt with in the same way as any other method.
Isn't as bad as it looks. It's essentially what we're really doing in Ruby with "print", though Ruby's equivalent to sys.stdout is the global variable $stdout or the constant STDOUT. We could rewrite the Ruby code as:
Also a point of interest is that Ruby's methods may look like language constructs because they can be called with or without parentheses. Parentheses may be considered confusing for simple examples, or they may be required to clarify more complicated code. When a method takes no arguments, though, there's absolutely no reason to include parentheses. Certainly "name.strip" is a bit easier on the typing fingers than "name.strip()". It should also be noted that Python lacks a syntactic shortcut to get input from the user. The Ruby version of the Python way would be:
The method used to insert the variable "name" into the string at the end of the Python example is roughly equivalent to:
The Python example has advantages though. If I had multiple values to insert, as in the following example, I don't have to remember the order of them when I list the trailing variables.
|
Author: | wtd [ Sat Jun 26, 2004 12:46 am ] | ||||||||||||
Post subject: | |||||||||||||
Python is distinctly more strict about syntax than Ruby, so the conversion of "Decsion, decision..." will be relatively straightforward. In Ruby
In Python
In Ruby
In Python
In Ruby
In Python
Compare and Contrast Python foregoes equivalents to Ruby's case...when...else...end construct and the lack of an equivalent for "then" means that this can't be rolled up into a one-liner. As well, such statements in Python don't return a value. Neither for that matter does assignment (the = operator). The postfix notation is missing too, along with the negative version of "if" ("unless"). "elsif", however, is further shortened to simply "elif". Regular expressions are not a part of the Python language as they are in Ruby, but are implemented through a separate module. "re.compile" takes a pattern and creates a regular expression object which can be matched against a string variable. |