Why "Range" not worked on "to_ary"?

(1…9).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

(1…9).to_ary
NoMethodError: undefined method to_ary' for 1..9:Range from (irb):2 from /usr/bin/irb:12:in

In the below code why “Range” not worked on “to_ary” ?

Try looking at the methods available to a Range.

$ irb
irb(main):001:0> a = (1…9)
=> 1…9
irb(main):002:0> a.public_methods.sort
=> ["==", “===”, “=~”, “id”, “send”, “all?”, “any?”, “begin”,
“class”, “clone”, “collect”, “count”, “cycle”, “detect”, “display”,
“drop”,
“drop_while”, “dup”, “each”, “each_cons”, “each_slice”,
“each_with_index”,
“end”, “entries”, “enum_cons”, “enum_for”, “enum_slice”,
“enum_with_index”,
“eql?”, “equal?”, “exclude_end?”, “extend”, “find”, “find_all”,
“find_index”, “first”, “freeze”, “frozen?”, “grep”, “group_by”, “hash”,
“id”, “include?”, “inject”, “inspect”, “instance_eval”, “instance_exec”,
“instance_of?”, “instance_variable_defined?”, “instance_variable_get”,
“instance_variable_set”, “instance_variables”, “is_a?”, “kind_of?”,
“last”,
“map”, “max”, “max_by”, “member?”, “method”, “methods”, “min”, “min_by”,
“minmax”, “minmax_by”, “nil?”, “none?”, “object_id”, “one?”,
“partition”,
“private_methods”, “protected_methods”, “public_methods”, “reduce”,
“reject”, “respond_to?”, “reverse_each”, “select”, “send”,
“singleton_methods”, “sort”, “sort_by”, “step”, “taguri”, “taguri=”,
“taint”, “tainted?”, “take”, “take_while”, “tap”, “to_a”, “to_enum”,
“to_s”, “to_yaml”, “to_yaml_properties”, “to_yaml_style”, “type”,
“untaint”, “zip”]

And there we have it to_a

yes,you are right. Now I have one thing to say that-

Array#try_convert(obj) : If obj is not already an array, attempts to
convert it to one by calling its ‘to_ary’ method.

I have no handy example for that method here to paste,thus couldn’t.
Question is why then such implementation?

On Sat, Feb 23, 2013 at 2:35 PM, Xavier R. [email protected] wrote:

yes,you are right. Now I have one thing to say that-

Array#try_convert(obj) : If obj is not already an array, attempts to
convert it to one by calling its ‘to_ary’ method.

I have no handy example for that method here to paste,thus couldn’t.
Question is why then such implementation?

#to_ary is used to convert things that are fundamentally array-like,
i.e. they can be used in places (usually standard library methods)
where arrays can be used. A range is not fundamentally like an array,
because it doesn’t consist of a finite number of elements (or really
any “elements” at all unless you want to count the endpoints). #to_a
is used to convert things in a way that’s dictated by convention,
rather than a way that’s inherent to the data themselves.

I don’t think ranges can act as arrays that way, it is not guaranteed
that they are finite.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs