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"

puts s.methods

print dir(s)

#find out more about a method using python

#-----view object's class-----


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

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

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

#---ternary operators

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

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

puts "Length of hash is same as string, #{h.length} or #{h.size} "

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..3] #=>[2,3]

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

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

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

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)
        break if val.to_s.length < 1
        yield  self.slice!(0..(sizeOfGroup.abs-1))

here is the code I used to test with

string = "12345678910" 
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

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.