"E S" <eero.saynatkari@kolumbus.fi> schrieb im Newsbeitrag
news:20050125052315.WKZL2811.fep31-app.kolumbus.fi@mta.imail.kolumbus.fi...
B) You can use Enumerable:
class String
def str_replace(what, with)
s = self.collect do |c|
with if c === what
end
end
end
I don't think this will work as String#each does not yield single
characaters but "lines".
You are right, it doesn't
But I already manage to make String.str_replace (case sensitive) and String.str_ireplace (incase sensitive) pass all my unit test
I already check there is not same function yet build in Ruby object
Thanks a lot for giving me some idea
But I already manage to make String.str_replace (case sensitive) and
String.str_ireplace (incase sensitive) pass all my unit test
I already check there is not same function yet build in Ruby object
But there is: String#gsub()
def str_replace(what, with)
re = Regexp.new(Regexp.quote(what))
self.gsub(re) {with}
end
def str_ireplace(what, with)
re = Regexp.new(Regexp.quote(what), Regexp::IGNORECASE)
self.gsub(re) {with}
end
end
raise "Failed" if "aaaaaaaa0aaaaaa3aaaaaaa".str_ireplace("AA", "") != "03a"
raise "Failed" if "aaaaaaaa0aaaaaa3aaaaaaa".str_ireplace("A", "") != "03"
YS
Thanks you verymuch
your scripts pass the following test
require 'test/unit'
class Test_string_ireplace < Test::Unit::TestCase
def test_replace1
source = 'rasa FiSh bakar'
check = 'rasa ikan bakar'
assert_equal(check,source.str_ireplace('fIsh','ikan')) end
def test_replace2
source = 'dunia ini panggung sandiwara'
check = 'dunia ini panggung codewara'
assert_equal(check,source.str_ireplace('sandi','code')) end
def test_replace3
source = 'dunIa inI panggung sandiwara'
check = 'duneKoa eKoneKo panggung sandeKowara'
assert_equal(check,source.str_ireplace('i','eKo')) end
def test_replace4
check = 'dunia ini panggung sandiwara'
source = 'dunekoa ekoneko panggung sandekowara'
assert_equal(check,source.str_replace('eko','i')) end
def test_replace5
check = ' ini panggung sandiwara'
source = 'dunia ini panggung sandiwara'
assert_equal(check,source.str_replace('dunia','')) end
def test_replace6
check = 'ini panggung sandiwara'
source = 'dunia ini panggung sandiwara'
assert_equal(check,source.str_replace('dunia ','')) end
def test_replace7
check = '03'
source = 'aa0a3aa'
assert_equal(check,source.str_replace('a',''))
check = '03'
source = 'aaaaaa0aaaa3aaaaaaaa'
assert_equal(check,source.str_replace('aa',''))
check = '03'
source = 'aaaaaa0aaaa3aaaaaaaa'
assert_equal(check,source.str_replace('aa',''))
check = '03'
source = '0 3'
assert_equal(check,source.str_replace(' ',''))
check = '0aa3'
source = '0 3'
assert_equal(check,source.str_replace(' ','a')) end
def test_case_sensitive1
source = 'dunIa ini panggung sandIwara'
check = 'dunIa ekoneko panggung sandIwara'
assert_equal(check,source.str_replace('i','eko')) end
end