How to Multiply "5X3" String in Ruby

How to split string into array as integers

ruby-1.9.2-p136 :001 > left, right =  "4x3".split("x").map(&:to_i)
=> [4, 3]
ruby-1.9.2-p136 :002 > left
=> 4
ruby-1.9.2-p136 :003 > right
=> 3

Call map on the resulting array to convert to integers, and assign each value to left and right, respectively.

Regex to constrain 3x2 string

three_by_two = /\A\d{3}x\d{2}\z/
if my_str =~ three_by_two

Decoded:

  • Start at the beginning of the string
  • 3 digits
  • a literal x
  • 2 digits
  • The end of the string

Regex to constrain 3x2 string

three_by_two = /\A\d{3}x\d{2}\z/
if my_str =~ three_by_two

Decoded:

  • Start at the beginning of the string
  • 3 digits
  • a literal x
  • 2 digits
  • The end of the string

Evaluating a piece of string as code in Ruby

str = "4 / 10 + 5 x 3"
eval(str.tr("x","*"))

If you want to keep the x you can translate it using tr.

eval can run anything, so don't try this with user input.

Looping in a spiral

Here's my solution (in Python):

def spiral(X, Y):
x = y = 0
dx = 0
dy = -1
for i in range(max(X, Y)**2):
if (-X/2 < x <= X/2) and (-Y/2 < y <= Y/2):
print (x, y)
# DO STUFF...
if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y):
dx, dy = -dy, dx
x, y = x+dx, y+dy


Related Topics



Leave a reply



Submit