From: Josh Cheek Date: 2012-02-07T08:31:05+09:00 Subject: Re: Using _ like in Scala? --e89a8f2356973d2d5d04b8540ea2 Content-Type: text/plain; charset=ISO-8859-1 On Mon, Feb 6, 2012 at 12:54 PM, Marc Heiler wrote: > fruits = %w( apple banana orange ) > > fruits.each { puts _ } > > vs > > fruits.each { |f| puts f } > > I was told that scala uses _ to denote as default block argument (the > first one. I am not sure what else scala does) > > Could _ be used in Ruby to allow the same? > > It could, but I doubt anyone would go for it. As an example, there are already language features that add variables: /a(?.)c/ =~ "abc" middle_char # => "b" > The question is actually a bit larger. I am wondering whether Ruby could > reserve a set of key-names for variables. > > In this example it could use _ but it could perhaps make better use of > it too. Perhaps even something like: > > array_fruits = %w( apple banana orange ) > > ^^^ And the above would keep the variable permanently as array type. > (With the convention being that the leading name array_ would indicate > that) > > I don't think this could be done without a serious overhaul of the type system, and I can't imagine why anyone would want to. It would even be harmful, consider something like this: def my_join(array_elements, delimiter="") array_elements.drop(1).each_with_object(array_elements.first.to_s) do |element, result| result << delimiter.to_s << element.to_s end end my_join [1, 2, 3], " " # => "1 2 3" my_join 1..3, " " # => raises some kind of error Now it will break because we passed it a range instead of an array, even though it's perfectly capable of performing this operation. Besides, array_... is spammy (clutters the code with useless information). The convention is to pluralize the argument if it's a collection of items, which reads very well and sufficiently informative. So I don't think there is a use case for it, there is definitely a use case against it, and it results in gross code. That said, I actually like static typing, but I consider a type not to be the class of the object, but rather the set of methods invoked on the object by whatever piece of code is using it (in this case, the type would be "an object that responds to `drop and first`" and probably being extended to `drop has an arity of one, and returns an object of type "responds to `each_with_object`" further refinements around arity and how many arguments it passes to the block). Of course this will never happen in Ruby because of how much overhead it would add and because it wouldn't be congruent with hyperdynamic dispatch (responding to methods that don't exist). --e89a8f2356973d2d5d04b8540ea2--