From: jamison edmonds Date: 2010-04-11T09:29:35+09:00 Subject: Re: end of sentience has ? y/n, if n please use one "string?"=o.k. --0-1479755436-1270945767=:17325 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable Thanks to=A0all=A0:)=20 =A0 --- On Thu, 3/25/10, brabuhr@gmail.com wrote: From: brabuhr@gmail.com Subject: Re: end of sentience has ? y/n, if n please use one "string?"=3Do.= k. To: "ruby-talk ML" Date: Thursday, March 25, 2010, 9:27 PM On Thu, Mar 25, 2010 at 8:32 PM, jamison edmonds w= rote: > Still new to programing. > I'm making a magic 8 ball clone, for fun and to learn by, console based f= or 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 sa= y, need a question with a ? mark at end please. There are quite a few ways to approach this problem.=A0 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 =3D gets abcdefg? =3D> "abcdefg?\n" I'm assuming you don't care about the newline on the end of gets-ed string.=A0 So, I'll chomp it first: http://ruby-doc.org/core/classes/String.html#M000819 >> a.chomp =3D> "abcdefg?" >> a =3D> "abcdefg?\n" >> a.chomp! =3D> "abcdefg?" >> a =3D> "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] =3D> "?" # substring of length 1 from last (-1) position >> a[-1,1] =3D> "?" (There is also simply a method like a[-1]: =A0 >> a[-1] =A0 =3D> 63 which returns the code for position -1, if you look 63 up in an ASCII table, you'd see that it corresponds to ?: =A0 >> 63.chr =A0 =3D> "?" 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 =3D a.split('') =3D> ["a", "b", "c", "d", "e", "f", "g", "?"] >> b.last =3D> "?" 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(/\!$/) =3D> nil # does a have a ? at the end >> a.match(/\?$/) =3D> # =0A=0A=0A --0-1479755436-1270945767=:17325--