PythonRubyTranslator
		
		
		
		
		
		Jump to navigation
		Jump to search
		
		
	
| Python | Ruby | 
|---|---|
| objects and inheritance | |
| class FooClass(BarClass): | class FooClass < BarClass | 
| class FooClass: | class FooClass | 
| isinstance(object, Class) or issubclass(type(object), Class) | object.is_a? Class | 
| type(object) == Class | object.class == Class | 
| multiple inheritance / mix-ins | |
| class Foo(BaseClass, MixIn): | class Foo < BaseClass  include MixIn  | 
| public data (attributes) on classes | |
| self.foo = 'foo' | attr_reader: foo, attr_accessor: foo or attr_writer: foo | 
| private data (attributes/instance variables) | |
| self.__foo = 'foo' | @foo = 'foo' instance variables are private by default | 
| print, str, repr | |
| print("foo") | print "foo" | 
| print(repr("foo")) | p "foo" | 
| string slices | |
| "foobar"[2:4] | "foobar"[2...4] or "foobar"[2..3] | 
| "foobar"[3:] | "foobar"[3..-1] | 
| "foobar"[:3] | "foobar"[0...3] or "foobar"[0..2] | 
| "foobar"[-1:0:-2] | Ruby doesn't allow step in slice syntax | 
| is a value in a collection? | |
| value in collection | collection.index(value) | 
| comparison | |
| 0 < number < 100 | 0 < number and number < 100 or (0+1...100) === number  | 
| function declaration and invocation | |
| key-word arguments | |
| def func(arg1, arg2, key3='val3', key4='val4'): | Ruby does not have keyword arguments. key=value pairs in function definitions are positional arguments with default values. | 
| arbitrary positional arguments | |
| def func(arg1, arg2, *args): | def func(arg1, arg2, *splat) | 
| func(arg1, arg2, arg3, arg4) | func(arg1, arg2, arg3, arg4) | 
| default argument value interpretation: expression can be [], {}, "foo", etc | |
| def func(arg=expression): | def func(arg=expression) | 
| expression is evaluated when the function is defined | expression is reevaluated each time the function is called | 
| run module as a script | |
| if __name__ == '__main__': | if __FILE__ == $0 | 
| exception handling | |
try: raise FooException except FooException: # handle FooException else: # do something if no errors finally: # do something always  | 
begin raise FooException rescue Exception => e # handle FooException else # do something if no errors ensure # do something always end  |