Ruby to Python Primer

If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It’s not Ruby 😀 , but it can get the job done. Here is a quick list of similarities between the two languages. I hope it helps… don’t forget to this list in the comments section 😉

#-----find object methods-----
s="hello, I am a string"

#ruby
puts s.methods

#python
print dir(s)

#find out more about a method using python
help(s.split)

#-----view object's class-----
#ruby
s.class

#python
s.__class__

#------Iterate hashes-------

#ruby
h.each{|key,value| puts "#{key}, #{value}"}

#python
for key,value in h.iteritems():
print key, value

#---ternary operators

#ruby
condition ? var = x : var = y

#python.. not exactly an operator, but you get the meaning
#---- var = y if condition is false
var = x if condition else y

#----lengths------
#ruby
s="hello, I am a string"
puts "Length of string is #{s.length} or #{s.size}"

h={:one=>2,:three=>4}
puts "Length of hash is same as string, #{h.length} or #{h.size} "

#python
print("This is the length of a string %s" % len("string"))
print("number of key/value pair= %d" % len({'one':1,'two':2}))

#---slicing lists/arrays
l=[1,2,3,4,5]

#ruby
l[1..3] #=>[2,3]

#python
l[1:3] #=>[2,3]

#--print string multiple times-----

#ruby
4.times{print "hello"} #=> hellohellohellohello

#python
print("hello" * 4) #=> hellohellohellohello

Leave a Reply

Your email address will not be published. Required fields are marked *