Tag Archives: Ruby Questions

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

Adding Functionality to Ruby Strings

Ok, here is the scoop. I was working on a project using Ruby and needed to grab three characters from a string skipping one character in between.

ex –>  “123456789”    would become 234 and 567

I thought this would be a great opportunity to try out blocks in Ruby and test open classes

class String
   def blocker(sizeOfGroup,offset)
     while(val=self.slice!(0..offset.abs-1))
        break if val.to_s.length < 1
        yield  self.slice!(0..(sizeOfGroup.abs-1))
      end
  end
end


here is the code I used to test with


string = "12345678910" 
ary=[] 
string.blocker(3,-1){|v| ary.push(v)}
ary.each{|i|puts i}
puts "her is ary "+ary.inspect 

And this is the result.

>>> test.rb

234
678
10
her is ary ["234", "678", "10"]

This was definitely a fun experiment and I can't wait to try out more stuff. If you haven't played around with blocks, give it a try...you just might like it.