--0-1479755436-12709457677325
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable

Thanks to 


--- On Thu, 3/25/10, brabuhr / gmail.com <brabuhr / gmail.com> wrote:


From: brabuhr / gmail.com <brabuhr / gmail.com>
Subject: Re: end of sentience has ? y/n, if n please use one "string?"=o.k.
To: "ruby-talk ML" <ruby-talk / ruby-lang.org>
Date: Thursday, March 25, 2010, 9:27 PM


On Thu, Mar 25, 2010 at 8:32 PM, jamison edmonds <jamison2000e / yahoo.com> 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(/\?$/)
=> #<MatchData "?">




      
--0-1479755436-12709457677325--