8
A
回答
10
由於浮雕狀態,String#include
調用rb_str_index
。該功能依次調用rb_memsearch
,該功能實現Rabin-Karp string search algorithm,根據this post的ruby-forum.com
。
5
這是實際執行的String#include?
:
static VALUE
rb_str_include(VALUE str, VALUE arg)
{
long i;
StringValue(arg);
i = rb_str_index(str, arg, 0);
if (i == -1) return Qfalse;
return Qtrue;
}
因此實際使用的算法可以在rb_str_index找到。在他的回答
6
Ruby語言規範沒有規定任何特定的算法。每個實現可以使用他們想要的任何算法。
例如,在Rubinius,String#include?
呼叫String#find_string
:
def include?(needle)
if needle.kind_of? Fixnum
needle = needle % 256
str_needle = needle.chr
else
str_needle = StringValue(needle)
end
!!find_string(str_needle, 0)
end
String#find_string
反過來經由string_index
原語實現:
def find_string(pattern, start)
Rubinius.primitive :string_index
raise PrimitiveFailure, "String#find_string failed"
end
的原語由rubinius::String::index
功能實現:
// Rubinius.primitive :string_index
Fixnum* index(STATE, String* pattern, Fixnum* start);
Fixnum* String::index(STATE, String* pattern, Fixnum* start) {
native_int total = size();
native_int match_size = pattern->size();
if(start->to_native() < 0) {
Exception::argument_error(state, "negative start given");
}
switch(match_size) {
case 0:
return start;
case 1:
{
uint8_t* buf = byte_address();
uint8_t matcher = pattern->byte_address()[0];
for(native_int pos = start->to_native(); pos < total; pos++) {
if(buf[pos] == matcher) return Fixnum::from(pos);
}
}
return nil<Fixnum>();
default:
{
uint8_t* buf = byte_address();
uint8_t* matcher = pattern->byte_address();
uint8_t* last = buf + (total - match_size);
uint8_t* pos = buf + start->to_native();
while(pos <= last) {
// Checking *pos directly then also checking memcmp is an
// optimization. It's about 10x faster than just calling memcmp
// everytime.
if(*pos == *matcher &&
memcmp(pos, matcher, match_size) == 0) {
return Fixnum::from(pos - buf);
}
pos++;
}
}
return nil<Fixnum>();
}
}
+0
+1表示它完全實現特定。 –
相關問題
- 1. Ruby中的String#方法vs String#方法()
- 2. 可否使用std :: string #include <string>?
- 3. 使用Ruby的性能'include?'方法
- 4. Hyper String的算法
- 5. Ruby Array/include?/。
- 6. Ruby DataMapper:未定義的方法`include?'
- 7. 如何在Ruby的File類中使用.include?類似的方法?
- 8. 有沒有辦法使用! .include中的運算符?方法?
- 9. 用於排列算法的Ruby代碼中的錯誤?
- 10. Jenkins中「Include Regions」的用法
- 11. Ruby Array#include?給NoMethodError
- 12. 我何時使用#include <string>?
- 13. 編譯用#include <string>錯誤
- 14. 使用Include(string)方法包含幾個導航屬性
- 15. 用於PQDIF中CRC計算的算法
- 16. SharedPreferences.Editor類型中的putString(String,String)方法不適用於參數(String,char [])
- 17. 覆蓋Ruby的String類方法
- 18. 用於分佈式計算的Ruby庫?
- 19. IQueryable的確切值是什麼<T> Include(string path)方法?
- 20. Ruby方法調用每個使用「include Enumerable」
- 21. Ruby String#unpack
- 22. Ruby String#to_class
- 23. Ruby String merge
- 24. if語句也使用.include?和&&在ruby
- 25. String#include?只檢查第一個位置
- 26. replaceWith不適用於div-include
- 27. Ruby中的運算符和方法
- 28. Ruby on Rails中的匹配算法
- 29. Ruby中的程序生成算法
- 30. 問題使用的#include <升壓/算法/ string.hpp>
你知道你可以看看[出處](http://apidock.com/ruby/String/include%3F),對不對? (然後查看C源代碼,至少對於字符串的包含。) –