It's been a while since the last update to my summary of changes in Ruby 1.9 and there are lots of new methods, a few syntactic changes and
fundamental changes in relation between Symbols and Strings.
Some highlights follow, but refer to the expanded changelog for the details (several RSS feeds with abridged ("differential") summaries
are available).
String
Strings are no longer Enumerable, but you can use string.lines to get an
enumerator:
"foo\nbar\n".lines.sort # => ["bar\n", "foo\n"]
There's also #bytes
"hello".bytes.to_a # => [104, 101, 108, 108, 111]
Several methods were added: #partition, #rpartition, #start_with?, #end_with?.
"hello, world".partition(/lo/) # => ["hel", "lo", ", world"]
Introspection
Methods returning a list of methods now use symbols instead of strings:
NilClass.instance_methods(false) # => [:to_a, :inspect, :yield, :to_f, :|, :to_s, :&, :to_i, :^, :nil?]
A couple methods were added to test whether an instance variable exists:
"".instance_variable_defined? :@a # => false
There's also Module#class_variable which is IMO misnamed:
class X; @a = 1 end
X.class_variable_defined? :@a # => true
X.class_variable_defined? :@@a
# ~> in `Module#class_variable_defined?': `@@a' is not allowed as an instance variable name (NameError)
@a is not a class variable (that'd be @@a) but a class instance variable.
This looks like a bug.
Syntax
Multiple splats were already allowed, and now you can also use mandatory
arguments after optional ones:
def m(a, b=nil, *c, d)
[a,b,c,d]
end
m(1,2) # => [1, nil, [], 2]
Symbols vs. Strings
Symbol is now a subclass of String (see also
this):
:foo.class.ancestors # => [Symbol, String, Comparable, Object, Kernel, BasicObject]
a = {:foo => 1, "bar" => 2}
a["foo"] # => 1
a[:bar] # => 2
:foo == "foo" # => true
"foo" == :foo # => true
:foo.gsub(/o/, "a") # => :faa
:foo.object_id # => -739527348
:foo.object_id # => -739527348
:foo[1..-1] # => "oo"
:foo.gsub!(/o/, "a") # => ERROR: in `String#gsub!': can't modify frozen string (RuntimeError)
Bugfixes and optimizations
These aren't listed in my changelog, since they don't affect the language
formally, but they're important nonetheless:
- small strings and arrays are packed in the associated RString/RArray structure. This is most important for one-char strings.
- several Array operations are now amortized O(1), and several memleaks were fixed
Change summary
Read more...
Read: Ruby HEAD's been evolving in the last 4 months