2

I'm new to Ruby. I'm trying to make some simple calculator program. So, basically what it's supposed to do is you input something like 4+2 and it outputs 6. Simple, right? So I thought. I'm trying to split a string at all the operation characters, so I made this quick regex thinking it would work. It didn't.

class Calculator 
def add(a,b)
    return a+b
end
def sub(a,b)
    return a-b
end
def div(a,b)
    return a/b
end
def mul(a,b)
    return a*b
end
end

operation = gets.split("[\/\+\-\*]")
print(operation)
sleep()

the sleep() is there to pause the console so I can take a look at my outputs. But right now, it's outputting ["4+2\n"]?? I don't know what I'm doing wrong. I need some help. (it should output ["4","+","2"]). Thanks in advance.

3 Answers 3

2

You don't need to escape every character inside of your character class. Consider the following:

operation = gets.gsub(/[^\d\/*+-]/, '').split(/([\/*+-])/)

or

operation = gets.split(/([\/*+-])/).map(&:strip)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, but use \d instead of 0-9
1

For a regular expression you want to use / instead of ":

operation = gets.split(/[\/\+\-\*]/) # ["4", "2\n"]

There's an extra newline remove that with strip:

operation = gets.strip.split(/[\/\+\-\*]/) # ["4", "2"]

But we lost the operator. Looking at the docs for split:

If pattern contains groups, the respective matches will be returned in the array as well.

Adding () in our regex creates a group. So then we have:

operation = gets.strip.split(/([\/\+\-\*])/) # ["4", "+", "2"]

3 Comments

thanks so much, but I don't understand the gets.strip.split. I understand that it strips the newline, but shouldn't it be gets.split(whatever).strip?
Split returns an array. strip operates on the string, I'm removing the newling before calling split.
-1 learn what to escape in regex before posting regex answers.
0

You can try the following code.

operation = gets.chomp.gsub(/[\/\+\-\*]/, ';\0;').split(";")
print(operation)

Execution result:

4+2/3*9-0
["4", "+", "2", "/", "3", "*", "9", "-", "0"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.