Ruby on Rails 具有方法 String#starts_with?
,该方法在 Ruby 中实现为
# File lib/active_support/core_ext/string/starts_ends_with.rb, line 22
def starts_with?(prefix)
prefix = prefix.to_s
self[0, prefix.length] == prefix
end
而 Ruby 从 1.8.7 版本开始,具有用 C 实现的方法 String#start_with?
static VALUE
rb_str_start_with(int argc, VALUE *argv, VALUE str)
{
int i;
for (i=0; i<argc; i++) {
VALUE tmp = rb_check_string_type(argv[i]);
if (NIL_P(tmp)) continue;
rb_enc_check(str, tmp);
if (RSTRING_LEN(str) < RSTRING_LEN(tmp)) continue;
if (memcmp(RSTRING_PTR(str), RSTRING_PTR(tmp), RSTRING_LEN(tmp)) == 0)
return Qtrue;
}
return Qfalse;
}
为什么他们不直接有一个从 starts_with?
链接到 start_with?
的别名?
他们是否希望保持与 Ruby 1.8.6 的兼容性,或者担心 start_with?
可能与 starts_with 有不同的行为?
,或者他们没有看到需要更新代码吗?
最佳答案
从您的代码来看,您手头的 Rails 版本似乎非常旧(<= 2.3.5)。由于此版本支持较旧的 Ruby 版本,而该版本还没有 start_with?
,因此他们手动实现了它。
但是,如果您查看上面的文件,您会发现他们使用了 ruby 内置方法(如果可用)。在较新的 Rails 版本中,放弃了 Ruby 1.8.6 支持,这些神奇的位 were removed ActiveSupport 现在提供无条件别名。
关于ruby-on-rails - 为什么 Rails 实现 String#starts_with 方法?而不是 start_with 的别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8044183/