Forum: Ruby How do I change change string to integer?

C03eeafd9928a98f6788b3d957225c3e?d=identicon&s=25 Michael Sm (michaels)
on 2014-02-23 12:46
Currently doing exercise 35 on Learn Ruby the hard way.
http://ruby.learncodethehardway.org/book/ex35.html

Heres the piece of code that I'm playing with:


def gold_room()
  puts "This room is full of gold.  How much do you take?"

  prompt; next_move = gets.chomp

  if next_move.include? "0" or next_move.include? "1"
    how_much = next_move.to_i()
  else
    dead("Man, learn to type a number.")
  end


Currently if the user inputs "0 Gold" or "1 Gold" it would convert that
string to an integer.

But if the user inputs "2 Gold" or "3 Gold" etc. it would return dead.

How do I make it so that it is not limited to numbers 0 and 1?

Thanks!
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (robert_k78)
on 2014-02-23 13:38
(Received via mailing list)
On Sun, Feb 23, 2014 at 12:46 PM, Michael Sorm <lists@ruby-forum.com>
wrote:
>
> But if the user inputs "2 Gold" or "3 Gold" etc. it would return dead.
>
> How do I make it so that it is not limited to numbers 0 and 1?

if /^(\d+)\s+(\S.*)$/ =~ next_move
  how_much = Integer($1)
  where = $2
  ...
else
  dead "Wrong input"
end

Kind regards

robert
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.