In this table I will compare some basic programming syntax and conventions between the Python and Ruby programming languages.
Programming element | Python | Ruby |
---|---|---|
Commenting code: Both use the pound # sign. |
# This is a comment |
# This is a comment |
Multi-line comments: |
""" This is a comment. This is a comment, too. This is a comment, too. """ |
=begin This is a comment. This is a comment, too. This is a comment, too. =end |
Identifying variable type: |
type(variable) |
variable.class |
Creating a variable that contains an int (Fixnum in Ruby): | age = 25 |
age = 25 negative_number = -25 |
Creating a variable that contains a float: | probability = 0.62 |
probability = 0.62 |
Creating a variable that contains a string: Python supports single, double, and triple quotes. |
state = 'North Dakota' state = "North Dakota" state = """North Dakota""" |
state = 'North Dakota' state = "North Dakota" |
Denoting string literals: Python uses an ‘r’ in front of the string. Ruby requires backslashes to escape characters. |
path = r'\path\to\some\files' path = r"\path\to\some\files" path = r"""\path\to\some\files""" |
path = "\\path\\to\\some\\files" path = '\\path\\to\\some\\files'
# prints That's right single_quotes1 = 'That\'s right' dbl_quotes1 = "That's right" # prints escape using \ single_quotes2 = 'escape using \\' dbl_quotes2 = "escape using \\" |
String Concatenation: | greeting = "Hello" + " world"
|
greeting = "Hello" + " world"
greeting = "Hello" greeting.concat(" World") |
Creating a list or array: | fruit_list = ['apple', 'banana', 'cherry'] |
fruit_list = ["apple", "banana", "cherry"] |
Getting the length of a list or array: | length = len(fruit_list) |
length = fruit_list.length
|
Python dictionary vs. Ruby hash: |
fruit = {'a':'apple', 'b':'banana', 'c':'cherry'} |
fruit = {"a" => "apple", "b" => "banana", "c" => "cherry"} |
Getting keys from a dictionary or object: | fruit_keys = fruit.keys() |
fruit_keys = fruit.keys |
Getting values from a dictionary or object: | fruit_values = fruit.values() |
fruit_values = fruit.values |
Adding key-value pairs to a dictionary or object: | fruit['o'] = 'orange' |
fruit[:'o'] = 'orange' fruit[:l] = 'lemon' fruit['o'] = 'orange' fruit.store("g", "grape") |
Deleting key-value pairs from a dictionary or object: | del fruit['c'] |
fruit.delete(:'o') fruit.delete('g') |
Python was invented in the late 1980s (1989) by Guido van Rossum. Ideas for Python were adopted from Modula-3 and Lisp.
Ruby was invented in the mid-1990s. According to Wikipedia:
Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.
According to its creator, Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp. It supports multiple programming paradigms, including functional, object-oriented, and imperative. It also has a dynamic type system and automatic memory management.