rb_ary_subseq(VALUE ary, long beg, long len) { VALUE klass; // 如果长度大于数组长度, 返回 nil. if (beg > RARRAY_LEN(ary)) return Qnil; if (beg < 0 || len < 0) return Qnil;
if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) { len = RARRAY_LEN(ary) - beg; } klass = rb_obj_class(ary); // 如果长度等于 0, 返回空数组. if (len == 0) return ary_new(klass, 0);
deftest_flexible_quotes_can_handle_multiple_lines long_string = %{# \n It was the best of times,# \n It was the worst of times.# \n } assert_equal 54, long_string.size end
deftest_here_documents_can_also_handle_multiple_lines long_string = <<EOS It was the best of times,# \n It was the worst of times.# \n EOS assert_equal 53, long_string.size end
# += 操作不会改变原始字符串. deftest_plus_equals_also_will_leave_the_original_string_unmodified original_string = "Hello, " hi = original_string there = "World" hi += there assert_equal "Hello, ", original_string end
# << 操作会修改源始字符串的. deftest_the_shovel_operator_modifies_the_original_string original_string = "Hello, " hi = original_string there = "World" hi << there assert_equal "Hello, World", original_string end
deftest_strings_can_be_split string = "Sausage Egg Cheese" words = string.split # 字符串分割的默认参数是 $; assert_equal ["Sausage", "Egg", "Cheese"], words end
deftest_strings_are_not_unique_objects a = "a string" b = "a string" # 值相等. assert_equal true, a == b # 但却不是同一个对象. assert_equal false, a.object_id == b.object_id end
# 在 MRI 版本里, 常量也是符号. in_ruby_version("mri") do RubyConstant = "What is the sound of one hand clapping?" deftest_constants_become_symbols all_symbols = Symbol.all_symbols assert_equal true, all_symbols.include?(:RubyConstant) end end
# 符号可以长的不太一样. deftest_symbols_with_spaces_can_be_built symbol = :"cats and dogs"
assert_equal symbol, symbol.to_sym end
# 符号也可以在内部插入值. deftest_symbols_with_interpolation_can_be_built value = "and" symbol = :"cats #{value} dogs"
assert_equal symbol, "cats and dogs".to_sym end
# 符号不是"不可变的"字符串, 它没有字符串的方法. deftest_symbols_do_not_have_string_methods symbol = :not_a_string assert_equal false, symbol.respond_to?(:each_char) assert_equal false, symbol.respond_to?(:reverse) end
# 连最基本的连接操作都不允许. deftest_symbols_cannot_be_concatenated assert_raise(NoMethodError) { :cats + :dogs } end
# 符号可以动态创建, 但是不推荐这样做. deftest_symbols_can_be_dynamically_created assert_equal :catsdogs, ("cats" + "dogs").to_sym end
about_regular_expressions.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 字符串可以像这样查找内容. deftest_a_regexp_can_search_a_string_for_matching_content assert_equal "match", "some matching content"[/match/] end
# 块中的代码甚至会给局部变量带来副作用. deftest_block_can_affect_variables_in_the_code_where_they_are_created value = :initial_value method_with_block { value = :modified_in_a_block } assert_equal :modified_in_a_block, value end