How can I get this code to work in my classes?
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/StartsEndsWith.html
I’d like to have all my custom methods located in one file, which I can
just include
How can I get this code to work in my classes?
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/StartsEndsWith.html
I’d like to have all my custom methods located in one file, which I can
just include
Skave R. [email protected] wrote:
How can I get this code to work in my classes?
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/
StartsEndsWith.html
require ‘rubygems’
require ‘activesupport’
include ActiveSupport::CoreExtensions::String
puts “howdy”.starts_with?(“ho”)
Is that the kind of thing you mean? m.
matt neuburg wrote:
Skave R. [email protected] wrote:
How can I get this code to work in my classes?
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/
StartsEndsWith.htmlrequire ‘rubygems’
require ‘activesupport’
include ActiveSupport::CoreExtensions::Stringputs “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, I missed the “class String” part. works fine now, thanks
Skave R. wrote:
[snip]
So I’d just like to add
def starts_with?(prefix)
prefix = prefix.to_s
self[0, prefix.length] == prefix
endto 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
Skave R. [email protected] wrote:
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs