How to input integer value to an array, based prec

2019-03-04 00:43发布

问题:

This question is an exact duplicate of:

  • How to input integer value to an array, based preceeding row + column values? [duplicate] 2 answers

For this following project, I am supposed to take input in the following format : R1C5+2 , which reads it as "in the table, Row 1 Column 5 ,add 2. Or in this format : R1C2C3-5 , which reads : "in the table, Row 1 Column 2-3, subtract 5. This is assuming that all numbers in the table are initially all 0.

Where I left Off:

I am having trouble finding a way to detect for a "+" or "-" to either add/subtract values in the table. Also, in providing a range to allow multiple additions when provided two C's or R's. For example: R1R5C2C3+2 (Row Range 1 - 5, Column Range 2 - 3, add 2).

Here is the following code:

puts 'Please input: '
x = gets.chomp

col = []
row = []

x.chars.each_slice(2) { |u|  u[0] == "R" ? row << u[1] : col << u[1] }

p col
p row

puts "Largest # in Row array: #{row.max}"
puts "Largest # in Columns array: #{col.max}" #must be in "" to return value

big_row = row.max.to_i
big_col = col.max.to_i


table = Array.new (big_row) { Array.new(big_col) }

回答1:

The method you are looking for is the =~ operator. If you use it on a string and give it a regexp pattern it will return the location of that pattern in the string. Thus:

x = 'R1C2C3-5'

x =~ /R/

returns: 0 since that is the position of 'R' in the string (counted just like an array 0,1,2...).

If you are unfamiliar with regexp and the =~ operator, I suggest you check out the Ruby doc on it, it is very valuable. Basically the pattern between the forward slashes get matched. You are looking to match + or -, but they have special meaning in regexp, so you have to escape them with a backslash.

x =~ /\+/
x =~ /\-/

but you can combine those into one pattern matcher with an OR symbol (pipe) |

x =~ /\+|\-/

So now you have a method to get the operator:

def operator(my_string)
  r = my_string.slice(my_string =~ /\+|\-/)
end

I would also use the operator to split your string into the column/row part and the numeric part:

op = operator(x)    # which returns op = '-'
arr = x.split(my_string(x))  # which returns an array of two strings ['R1C2C3', '5']

I leave further string manipulation up to you. I would read through this page on the String class: Ruby String Class and this on arrays: Ruby Array Class as Ruby contains so many methods to make things like this easier. One thing I've learned to do with Ruby is think "I want to do this, I wonder if there is already a built in method to do this?" and I go check the docs. Even more so with Rails!