user1239333
user1239333

Reputation: 85

ruby regular expressions

I am trying to create a program where a user enters four numbers using regular expressions . If one of those numbers is 13 then the numbers to the left do not count toward the sum. My problem is creating an exception where none of the numbers equal 13. I cant seem to find a regular expression for my exception

puts "enter a number then hit enter four times"

number1 = STDIN.gets

number2 = STDIN.gets
number3 = STDIN.gets

number4 = STDIN.gets


if number1 =~ /13/ then
  puts number2.to_i + number3.to_i + number4.to_i
end

if number2 =~/13/ then
  puts number3.to_i + number4.to_i
end

if number3 =~/13/ then
  puts number4.to_i
 if number4 =~/13/ then
   puts "0"
 end
 if number1 != 13 or number2 != 13 or number3 != 13 or number4 != 13
   puts number1.to_i + number2.to_i + number3.to_i + number4.to_i
 end
end

Upvotes: 0

Views: 176

Answers (3)

jack
jack

Reputation: 172

If you want to use regular expressions, it should be mentioned that the following logic will yield true for more than just 13. It will also match 413, 131, 941771341, ...

if number1 =~ /13/ then

Changing it to if number =~ /^13$/ then would be more accurate, but not as good as using to to_i.

The other line in question...

if number1 != 13 or number2 != 13 or number3 != 13 or number4 != 13

...doesn't work as expected because you are comparing a string to a number, and the logic join should be and. Comparing it to "13" won't work either, since it is actually "13\n". You can use number1.to_i != 13 and number2.to_i != 13 or something like number1 !~ /^13$/ and number2 !~ /^13$/ ... You could also figure out where to use an else statement in there.

I really recommend studying the other answers though. They are far more elegant and Rubyesque.

Upvotes: 0

gmalette
gmalette

Reputation: 2469

I don't mean to rewrite your whole logic but you could use the enumerable module and do something like

puts "enter a number then hit enter four times"

# Collect 4 numbers
numbers = 4.times.map{ STDIN.gets }.reverse

# Take the numbers until the first 13, then sum them
puts numbers.map(&:to_i).take_while{ |a| a != 13 }.reduce(:+)

Upvotes: 6

user1182000
user1182000

Reputation: 1635

gmalette, that's really interesting syntax. I learned from it. However, you're code needs to have the take_while method count backwards from the end of the array. Also, the reduce method will add the stings together. So "44" + "55" = "4455". This works:

puts "Enter four numbers separated by spaces:"
numbers = STDIN.gets.split
numbers.reverse!.collect! {|s| s.to_i }
puts numbers.take_while{ |a| a != 13 }.reduce(:+)

That reduce statement is really interesting.

Upvotes: 2

Related Questions