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
Devise Password Reset from Rails Console
How to Initialize an Array in One Step Using Ruby
How to Seed the Production Database Using the Capistrano Gem
Fetch VS. [] When Working with Hashes
Difference Between Block and &Block in Ruby
Gracefully Shutting Down Sidekiq Processes
Get File Name and Extension in Ruby
Capistrano Deploy Fails After I Changed the Repository Url
Sorting an Array of Objects in Ruby by Object Attribute
Should I Specify Exact Versions in My Gemfile
Why Would We Put a Module Inside a Class in Ruby
Intermingling Attr_Accessor and an Initialize Method in One Class
Ide Sublime2 How to Find Method Definition
Is It a Bad Idea Do Divide the Models into Directories
Create a Ruby Method That Accepts a Hash of Parameters
Rails Byebug Did Not Stop Application
How to Set an Expectancy on Should_Receive and Have It Execute the Original Code