def digit?
\^/d*$\ =~ self ? "true" : "false"
end
...
Can someone please have a look at my code and tell me what I'm doing wrong?
As Nemo said, you'll be returning the string versions of true and
false, rather than raw literal true and false, because of the quotes.
To understand his second correction, though, you need to realize that
in order to use special "escape code" chars like "d" to denote a
digit, the preceding char must be a *backslash*, not a normal slash.
If you want to use his solution, though, you'll need to remove the
spaces he put inside it. (Yeah, regex syntax is abstruse.)
Second, regexes work on strings. If you call it on, for instance, 6
(as opposed to "6"), you're going to get "TypeError: no implicit
conversion of Fixnum into String". So, you need to convert the
argument to a String if it isn't one already.
A couple other suggestions though:
- Think about what happens if you feed it something unusual, like
empty string, or maybe even nil. Try it. Is that what you wanted to
have happen? If not, how can you fix it?
- If you weren't writing it, but saw that there was a method called
"digit?", and you didn't see the code, what expectations would that
set in your mind, about what sort of test its applying? Does that
match what yours does? If not, is there maybe a better name for
yours? Good naming will help people understand your code, though it
can be difficult. (There's an old saying that there only are two
really hard things in computer science: cache invalidation, and naming
things. BTW, this has given rise to the joke that there only are two
really hard things in computer science: cache invalidation, naming
things, and off-by-one errors.)
···
On Fri, Jan 29, 2016 at 9:59 AM, angela ebirim <cebirim@gmail.com> wrote:
--
Dave Aronson, consulting software developer of Codosaur.us,
PullRequestRoulette.com, Blog.Codosaur.us, and Dare2XL.com.