problem with "starts_with?"

S

Skave Rat

matt said:
require 'rubygems'
require 'activesupport'
include ActiveSupport::CoreExtensions::String

puts "howdy".starts_with?("ho")

Is that the kind of thing you mean? m.

hm, yea, but the problem is it's not rails but simple ruby.
So I'd just like to add

def starts_with?(prefix)
prefix = prefix.to_s
self[0, prefix.length] == prefix
end

to my code where I can use it on all strings inside.
 
J

John Winters

Skave Rat wrote:
[snip]
So I'd just like to add

def starts_with?(prefix)
prefix = prefix.to_s
self[0, prefix.length] == prefix
end

to my code where I can use it on all strings inside.

Surely you just do it? (Or have I missed the point somehow?)


class String
def starts_with?(prefix)
prefix = prefix.to_s
self[0, prefix.length] == prefix
end
end

candidate = "Banana"
puts candidate.starts_with?("Da").to_s


Just make sure the first bit gets executed somewhere early on in your
application's run.

HTH
John
 
M

matt neuburg

Skave Rat said:
matt said:
require 'rubygems'
require 'activesupport'
include ActiveSupport::CoreExtensions::String

puts "howdy".starts_with?("ho")

Is that the kind of thing you mean? m.

hm, yea, but the problem is it's not rails but simple ruby.
So I'd just like to add

def starts_with?(prefix)
prefix = prefix.to_s
self[0, prefix.length] == prefix
end

to my code where I can use it on all strings inside.

Ah - so you mean you want to implement starts_with? yourself. Sure,
then, as you've been shown, you can just implement a method on String.

However, please do note that my solution *is* "simple ruby", not rails.
What I showed you is how I would do it. In other words, there is nothing
wrong with "stealing" existing code by requiring (and possibly
including) an existing module. I do this kind of thing all the time. For
example, I don't use rails, but I do use the active support -> string
core extensions quite a bit (esp. the unicode stuff). Why reinvent the
wheel? Sure, it happens that in your case it's a very easy wheel to
reinvent; I'm just saying that snarfing up stuff from libraries into
your scripts isn't something to run away from, it's something to run
towards. It's the Ruby way. m.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top