From: brabuhr@... Date: 2010-03-26T11:27:48+09:00 Subject: Re: end of sentience has ? y/n, if n please use one "string?"=o.k. On Thu, Mar 25, 2010 at 8:32 PM, jamison edmonds wrote: > Still new to programing. > I'm making a magic 8 ball clone, for fun and to learn by, console based for now. :) > > I need a few good examples on how to detect if input has a question mark at the end (more than one example/explanation preferably.) > > So, I GETS a question in my .rb and if "string?" o.k. else I'd like to say, need a question with a ? mark at end please. There are quite a few ways to approach this problem. If you haven't already, you can find an overview of various string methods here: http://www.ruby-doc.org/core/classes/String.html First let's gets a string: >> a = gets abcdefg? => "abcdefg?\n" I'm assuming you don't care about the newline on the end of gets-ed string. So, I'll chomp it first: http://ruby-doc.org/core/classes/String.html#M000819 >> a.chomp => "abcdefg?" >> a => "abcdefg?\n" >> a.chomp! => "abcdefg?" >> a => "abcdefg?" Strings in ruby can in some ways behave like arrays (responding to []): http://ruby-doc.org/core/classes/String.html#M000771 # substring from last (-1) position to last position (-1) >> a[-1..-1] => "?" # substring of length 1 from last (-1) position >> a[-1,1] => "?" (There is also simply a method like a[-1]: >> a[-1] => 63 which returns the code for position -1, if you look 63 up in an ASCII table, you'd see that it corresponds to ?: >> 63.chr => "?" but, this behavior is different from ruby 1.8 and ruby 1.9, which is why I almost didn't mention it here.) Strings can also be turned into arrays: http://ruby-doc.org/core/classes/String.html#M000803 >> b = a.split('') => ["a", "b", "c", "d", "e", "f", "g", "?"] >> b.last => "?" And strings can also be matched against patterns: http://ruby-doc.org/core/classes/String.html#M000778 http://www.regular-expressions.info/ruby.html # does a have a ! at the end >> a.match(/\!$/) => nil # does a have a ? at the end >> a.match(/\?$/) => #