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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
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
This topic is locked and can not be replied to.