News for hackers. Stuff that matters.
Re:Ruby is beautiful (but I'm moving to Python) by axod on Sunday November 28, 2010 @03:41PM (#1948234)
FWIW, I come from Java and find Ruby to be fairly ugly.

It's all subjective, but I prefer concise, exact non ambiguous readable code.

From a google for 'ruby sample code'...

http://www.fincher.org/tips/Languages/Ruby/

  print " with no line breaks."

  printf("\n\nprintf ... %7.2f,... %s.",3.14156,"me")
Eugh brackets are optional for invoking functions? So I can no longer just look for () after a name to determine what is a function invocation?

  def welcome(name)
   puts "howdy #{name}"
  end
"end"? Seriously? Verboseness... (This is one of the things that for me, makes ruby very ugly. It's needless verbosity and doesn't have any advantage over using {} ).

  "hello".upcase() => "HELLO"
  "hello".upcase => "HELLO"
Yuck. So how do you know what's a function and what's a variable?

  balance = -10.0
  puts "Bankrupt" unless balance > 0.0
Starting to look like cobol here... 'unless'? seriously? Why is that nicer than an if statement?

Java code has a very exact, easy to parse syntax. We all know it, and it's easy to learn - {} for code blocks, () for method invocations, etc

That's just for starters.

Re:Ruby is beautiful (but I'm moving to Python) by ashleyw on Sunday November 28, 2010 @05:32PM (#1948546)
1) If you're reading bad code, that could be a problem. But 99% of Ruby code I read has been written by people who know when they need parentheses/brackets to make the code readable (e.g. when it's not the only code on the line.) But there are tons of times when it's wonderful to be able to leave out the parentheses.

    -
2) It might be because I spend a lot of time with Ruby, but I much prefer `end`s to curly brackets, they're just easier on the eyes, especially when they're going to take up the entire line anyway:

    a
      b
        c
          d
          end
        end
      end
    end


    a {
      b {
        c {
          d {
          }
        }
      }
    }
Of course, at times I wish Ruby used indentation to declare structure, like Python.

    -
3) I don't think I've ever had that problem. If I'm calling `person.full_name`, I don't care if that's a variable, or a method joining first_name and last_name. And if I it was a method, ideally I'd have a corresponding `full_name=(str)` method defined too, so `person.full_name = "Joe Bloggs"` would work, and split the string into the first, last, and optional middle names.

    -
4) Why? Why not? What makes this easier to read?

    puts "Bankrupt" if balance <= 0.0



Ruby is a lot like the English language; when you're learning it as a second language, you're constantly confused and frustrated by it's weird syntax, but once you get past those initial hurdles, it just clicks. I love Ruby because I never feel like I'm programming in it, it almost feels like pseudo code that's not going to actually execute.

Essentially you could get any non-programmer to solve a problem on paper, and turn it into Ruby code which, without too much fuss, describes their process.

    # get the customers text file
    # each customer is on their own line, w/ their name and age separated by a comma
    # group the customers by age
    # show me the top 3 most common ages

    file = File.open('customers.txt')

    customers = []
    file.each_line do |line|
      name, age = line.split(",")
      customers << {:name => name, :age => age.to_i}
    end

    grouped_ages = customers \
                    .group_by{ |c| c[:age] } \
                    .map{ |c| [c[0], c[1].size] } \
                    .sort_by(&:last) \
                    .reverse

    grouped_ages.first(3).each do |age, size|
      puts "#{age} years old: #{size} customers"
    end
    
Four blocks of reasonably clean code (except the 3rd, that could be cleaned up a bit), which implement the four lines of plain english instructions.
Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Sunday November 28, 2010 @07:17PM (#1948831)
>I love Ruby because I never feel like I'm programming in it, it almost feels like pseudo code that's not going to actually execute.

Uh, you realise that describes any high level language, right? Ruby scores pretty low on the readability scale, about halfway between Perl and Python, but I find it's more familiarity with a particular language that determines how readable people find things.

Here's a quick Python version. The main thing to notice is that while the overall flow/structure is similar, I don't have a lot of { } << \ characters hanging around, and I don't have to chain blocks together since I have list comprehensions.

    from collections import defaultdict

    customer_file = (line.strip().split(',') for line in file('customers.txt'))

    grouped_ages = defaultdict(list)
    for name, age in customer_file:
        grouped_ages[age].append(name)

    age_lengths = sorted( [(len(names), age) for age, names in grouped_ages.items()], reverse=True )
    for length, age in age_lengths[:3]:
        print "%s years old: %s customers" % (age, length)
Re:Ruby is beautiful (but I'm moving to Python) by ataggart on Sunday November 28, 2010 @08:34PM (#1949013)
>Uh, you realise that describes any high level language, right?

I'm inclined to agree. I think the following also pretty closely matches the english requirements.

    (with-open [rdr (reader "customers.txt")]
      (->> (line-seq rdr)
        (map #(second (.split % ",")))
        (group-by identity)
        (map (fn [[age coll]] [age (count coll)]))
        (sort-by second (comparator >))
        (map first)
        (take 3)))
Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Monday November 29, 2010 @12:00AM (#1949438)
Looks kinda nasty to me, but then I'm not too familiar with Clojure/Lisp/whatever-the-hell-that-is ;)

I think one of the side effects of learning a Lisp is that you get a bit blasé about using map. Do you find list comprehensions easier than map/filter? Is there a list comprehension equivalent in Lisp, or would you have to write your own?

Re:Ruby is beautiful (but I'm moving to Python) by ataggart on Monday November 29, 2010 @07:13PM (#1952447)
It's clojure.

As for preference, given that map, filter, etc., are lazy, I like the clear visibility of each step working on each element of the sequence.

Clojure has a list comprehension, for, though using it here is more trouble than it's worth since you have to group and sort, both of which require you to step outside the comprehension and work on the whole list; that's why your code has multiple sections.

Instead, I see the example as just a selection/transformation process on sequences of data. Each step in the clojure code takes and returns a sequence of values (the ->> macro weaves them together):

  0. a sequence of lines from a file
  1. a sequence of age strings
  2. a sequence of [age, [ages...]] tuples
  3. a sequence of [age, count] tuples
  4. a sequence of [age, count] tuples sorted by count desc
  5. a sequence of age strings
  6. a sequence of up to 3 age strings
Fun detail: The with-open macro is akin to python's with statement, supports arbitrary number of items, is closed in reverse order of their appearance, and didn't require a change to the language to implement ;)
Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Monday November 29, 2010 @07:52PM (#1952560)
Well, you need to sort by occurrences, so you have to work with the whole list in this particular case. I also don't think that having two sections is a particularly big deal, since semantically you're working with two separate things too (the list of people+ages, and the aggregated list of names+a count). If you wanted to do something else too (say, list the names as well) then having an intermediate form can come in handy.

Also, I'm pretty sure that writing a macro counts as 'changing the language', although that line's a bit blurred when you're talking about lisps ;) ;)

Re:Ruby is beautiful (but I'm moving to Python) by ataggart on Monday November 29, 2010 @11:13PM (#1953047)
Note, I wasn't criticizing the python implementation. It's a perfectly reasonable way to model the problem.

You brought up list comprehensions, and something about being "blasé about using map". I wanted to show how a different way of modeling the problem yields a different structure to the code (namely, as a chain of transformations on sequences).

One is not better or worse than another. One of the things I enjoyed most about learning clojure was forcing myself to think in these different ways.

Re:Ruby is beautiful (but I'm moving to Python) by pivo on Monday November 29, 2010 @08:20PM (#1952638)
I wanted to reply to anthonyb's comment about macro use changing the language in the clojure example but couldn't, I guess because it's too deeply nested.

Anyway, ataggart didn't write a macro he just used one that's already part of the language. Using a macro does not count as changing the language.

Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Monday November 29, 2010 @10:46PM (#1952975)
He was talking about with-open not needing a change to the language to implement. In other words, Python's with statement did need a change to the language, but then Python is a (semi-)interpreted language written in C, so it's a cheap shot - just what I'd expect from a dirty Lisp hacker ;)
Re:Ruby is beautiful (but I'm moving to Python) by ashleyw on Monday November 29, 2010 @06:23AM (#1949971)
Well, I was comparing it to something like Java. Though Python still scores far lower on my readability scale. It's seems like it's halfway to being minified, the lines are chock-a-block.

Also, this is a better version in Ruby:

    file = File.open('customers.txt')

    customers = {}
    file.each_line do |line|
      name, age = line.split(",")
      customers[age.to_i] ||= []
      customers[age.to_i] << name
    end

    grouped = customers.sort_by{|age, names| names.count}.reverse

    grouped.first(3).each do |age, customers|
      puts "#{age} years old: #{customers.count} customers"
    end

…not sure what I was thinking before, it was late.
Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Monday November 29, 2010 @05:39PM (#1952117)
> Python still scores far lower on my readability scale. It's seems like it's halfway to being minified, the lines are chock-a-block.

That's likely because you're not used to reading Python. For me, Ruby seems unreadable - you have all these weird << and ||= assignments, {||} blocks, etc. I don't parse those as well, because I don't program much Ruby. I'm sure if I did, it'd make a lot more 'intuitive' sense - ditto for you and Python's list comprehensions.

Re:Ruby is beautiful (but I'm moving to Python) by nwmcsween on Wednesday December 01, 2010 @12:29AM (#1956943)
<< and >> are rudimentary it's almost always exactly the same as unix dated from 1970's redirection. e.g: $ echo 'crap' >> somefile.txt. ||= reads as 'or equal', simple.
Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Monday December 06, 2010 @12:31AM (#1974063)
Yeah, I know what they do - eg. ||= being a Ruby idiom for 'set if this currently evaluates as false'. The point is that because I don't often program in Ruby, it's less readable (for me). Similarly, if you're not used to list comprehensions they'll seem opaque - but I use them all the time, and find them far more readable than equivalent expressions using map/filter.

That said, I do find the more "squiggly" languages (Perl, Ruby, C) to be less readable than the equivalent Scheme or Python, and I suspect that it's because there are fewer weird characters, so it's closer to English.

Re:Ruby is beautiful (but I'm moving to Python) by nwmcsween on Monday November 29, 2010 @03:48AM (#1949799)
Where is this readability scale? Would you mind giving a link for it, I wouldn't mind seeing how the 'readability' statistics came to be.
Re:Ruby is beautiful (but I'm moving to Python) by irahul on Monday November 29, 2010 @06:44AM (#1950007)
The groupby, if done using itertools, will cut some code.

  from itertools import groupby

  customer_data = (line.strip().split(',') for line in     file('customer.txt'))
  grouped_ages = groupby(customer_data, key=itemgetter(1))
  print sorted((len(list(g)), k) for k, g in grouped_ages)[-3:]
Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Monday November 29, 2010 @05:46PM (#1952136)
Ah yes, I'd forgotten about groupby. You'll also need to do a

   from operator import itemgetter
as well.
Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Sunday November 28, 2010 @11:55PM (#1949421)
A meta-question: why do people keep downvoting this comment? It's been up and down ever since I posted it. Is it that I'm critical of Ruby? I would've thought that if I take the time to write some code and respond in a rational way, then it should be worth at least a couple of karma. What gives?
Re:Ruby is beautiful (but I'm moving to Python) by axod on Monday November 29, 2010 @11:30AM (#1950801)
Trying to make a programming language modeled on plain english instructions is a recipe for disaster. Perhaps that's why I find your example at the end pretty ugly code.
Re:Ruby is beautiful (but I'm moving to Python) by rue on Sunday November 28, 2010 @04:13PM (#1948316)
It cannot please everyone so if you are happy with a less "conversational" language, stick with it. "Unless", for example, is what I think to myself so "if not" is a suboptimal translation thereof.

I would point out, however, that printf is fairly rarely used and that I am not familiar with fincher.org in the context of sites to recommend newbs to learn Ruby from.

Removing the difference between accessing an attribute (variable) and invoking a method is a solid OO principle. You, as a client of the API, should not care how obj.foo is implemented.

Re:Ruby is beautiful (but I'm moving to Python) by adambyrtek on Sunday November 28, 2010 @05:27PM (#1948538)
> Removing the difference between accessing an attribute (variable) and invoking a method is a solid OO principle.

It's called the Uniform Access Principle[1] and the languages that don't take advantage of it often suffer from a getter/setter hell.

[1] http://en.wikipedia.org/wiki/Uniform_access_principle

Re:Ruby is beautiful (but I'm moving to Python) by anthonyb on Sunday November 28, 2010 @06:51PM (#1948779)
Er, that's one of those false dichotomy thingos. It's quite possible to have something like properties in Python: http://www.python.org/download/releases/2.2.3/descrintro/#pr...

Hey presto! Now you have the best of both worlds.

Re:Ruby is beautiful (but I'm moving to Python) by axod on Sunday November 28, 2010 @04:28PM (#1948361)
> "Removing the difference between accessing an attribute (variable) and invoking a method is a solid OO principle. You, as a client of the API, should not care how obj.foo is implemented."

I disagree. Code execution is not data access. They are very separate concepts.

Re:Ruby is beautiful (but I'm moving to Python) by rue on Sunday November 28, 2010 @05:03PM (#1948466)
Inasmuch this conversation is subjective, I just do not think that statement is objectively true. It is a basic OO principle that the outside world is not privy to the inner workings of an object (or class if you prefer).

Whether you like that or not is immaterial. You are free to avoid that aspect of OOP or the paradigm altogether.

Re:Ruby is beautiful (but I'm moving to Python) by axod on Sunday November 28, 2010 @05:13PM (#1948500)
I haven't studied OOP extensively in a strict setting, but I would have said that in the OO world, a property is completely separate to a method.

For example,

  class flower
  property color
  property numberOfPetals
  method pluckPetal()
  method water()
A property defines data about an object, and a method defines something you can 'do' with the object.

Could you give some pointers to the OOP principle that blurs the line between these two?

Re:Ruby is beautiful (but I'm moving to Python) by adambyrtek on Sunday November 28, 2010 @05:54PM (#1948623)
It's called the Uniform Access Principle, as I've already mentioned in a separate comment. Getting back to your example, it is not very useful without mentioning a language under examination. There is no single definition of OOP, and every language implements in a slightly different way.

There are languages where UAP is enforced by the syntax (eg. Eiffel, Smalltalk, Ruby) and languages where it's a matter of convention. But even in the latter it's considered a good practice to keep properties private and encapsulate them with accessors. Some even have dedicated features that help with that (auto-properties in C#, properties in Python).

Re:Ruby is beautiful (but I'm moving to Python) by masklinn on Monday November 29, 2010 @02:31AM (#1949693)
> I haven't studied OOP extensively in a strict setting, but I would have said that in the OO world, a property is completely separate to a method.

There is absolutely no reason for that, and the grandparent of all things object-oriented (Smalltalk) very strongly disagrees with you: everything is a message, and there are no properties.

> A property defines data about an object, and a method defines something you can 'do' with the object.

A getter method is a property and a method. Properties are irrelevant, access should be uniform, the implementation details of an object (whether a "property" provides direct access to internal data or not) is of no concern to the user of the object.

A property is nothing more than a method whose contract is "give me some data"

Re:Ruby is beautiful (but I'm moving to Python) by axod on Monday November 29, 2010 @04:27AM (#1949841)
That's a fine answer, and some people may find that a helpful way to organize programs.

However, for me, and the CPU, we treat code execution differently to data access.

Re:Ruby is beautiful (but I'm moving to Python) by philwelch on Monday November 29, 2010 @01:03PM (#1951128)
There's OOP qua Smalltalk/Kay, and then there's OOP qua Java. You're describing OOP qua Java, which is an ugly type of OOP designed for certain performance advantages.
Re:Ruby is beautiful (but I'm moving to Python) by axod on Monday November 29, 2010 @02:29PM (#1951457)
Don't be ridiculous.

1. It's not ugly

2. It's how CPUs work

3. It's how most people think

Re:Ruby is beautiful (but I'm moving to Python) by philwelch on Monday November 29, 2010 @03:02PM (#1951579)
1. By ugly, I mean less mathematically elegant. In Ruby, you say "paul.foo" and get foo from Paul. How Paul gets foo for you is up to Paul. Simple.

2. If you want a programming language that maps closely to how CPU's work, Ruby's definitely not for you. Assembly and C are for you.

3. I can't speak for most people. What I can say is that I can think in C and I can think in Ruby, and it doesn't seem difficult for me.

Re:Ruby is beautiful (but I'm moving to Python) by drylight on Sunday November 28, 2010 @05:23PM (#1948527)
A Java developer complaining about Ruby's supposed verbosity? What's the world coming to?! When one looks at Java code, 90% of it is just syntactic sugar, which doesn't add much to the actual working code. One has to filter through large amounts of white noise to get to the crux of the code. Not so with Ruby (and many other languages).
Re:Ruby is beautiful (but I'm moving to Python) by Twisol on Sunday November 28, 2010 @05:26PM (#1948534)
This is exactly what the original article was saying. ;) The languages take very different mindsets though, so if someone is actually happy with Java, then it's very possible that they don't have (or want) the right mindset for using Ruby.
Re:Ruby is beautiful (but I'm moving to Python) by axod on Sunday November 28, 2010 @06:20PM (#1948707)
Not really.

"public static final" is not particularly verbose. It's a one time upfront cost which defines a few flags. It's error free, since a typo in any of those keywords will be picked up.

It can also be automated easily etc.

But Ruby using 'end' etc instead of curly braces, that's going to add up to a lot of verbosity.

Re:Ruby is beautiful (but I'm moving to Python) by Twisol on Sunday November 28, 2010 @05:14PM (#1948505)
With regards to differentiating methods, that's simple. "obj.name" calls a method. An object's variables are hidden inside the object, so the only way to access them is via methods anyways.

Furthermore, variables can't be called. If you have a proc object in a variable, you use "myproc.call" to invoke it. The only ambiguity is between methods call within the same 'self' and local variables:

    def foo
      42
    end
    
    def bar
      puts foo #=> 42
      foo = 30
      puts foo #=> 30
      puts self.foo #=> 42
    end
In practice this isn't a big problem.
Re:Ruby is beautiful (but I'm moving to Python) by axod on Sunday November 28, 2010 @05:17PM (#1948510)
Ah I didn't realize Ruby does not have the ability to access properties of an object. That seems like a pretty big disadvantage.
Re:Ruby is beautiful (but I'm moving to Python) by Twisol on Sunday November 28, 2010 @05:18PM (#1948513)
That's because methods effectively -are- properties. See:

  class Foo
    attr_reader :bar
    
    def initialize (num)
      @bar = num
    end
  end
  
  puts Foo.new(42).bar
attr_reader is a class-level method that defines a getter method for the named variable. There's also attr_writer, for setting, and attr_accessor, for both at once.
Re:Ruby is beautiful (but I'm moving to Python) by axod on Sunday November 28, 2010 @06:21PM (#1948711)
... and people complain that Java is verbose???
Re:Ruby is beautiful (but I'm moving to Python) by ZitchDog on Sunday November 28, 2010 @08:06PM (#1948947)
Here it is, converted to java. You tell me which is more verbose.

    public class Foo
      int bar;
      
      public Foo(int bar) {
        this.bar = bar;
      }

      public int getBar() {
          return bar;
      }

      public static void main(String[] args) {
        System.out.println(new Foo(42).getBar());
      }
    }
Re:Ruby is beautiful (but I'm moving to Python) by slashdot on Sunday November 28, 2010 @11:19PM (#1949362)
Actually, in idiomatic java, it'd be even longer:

You should make bar private, and add a setter. After all, we might want to change the rules on setting bar sometime, and you wouldn't want to have to go back and change everywhere that accesses it...

Re:Ruby is beautiful (but I'm moving to Python) by masklinn on Monday November 29, 2010 @02:34AM (#1949700)
> You should make bar private

It's package-access by default, that's enough to hide it from the third-party users of the class.

> and add a setter

The original code uses `attr_reader` which defines a readonly "property". The Java translation is a single getter, with no way to set the value from outside the class.

Re:Ruby is beautiful (but I'm moving to Python) by axod on Monday November 29, 2010 @03:23AM (#1949769)
That's not really true. Why would you need a getBar() method in Java?

    public class Foo
      int bar;
      
      public Foo(int initBar) {
        bar = initBar;
      }

      public static void main(String[] args) {
        System.out.println(new Foo(42).bar);
      }
    }
Re:Ruby is beautiful (but I'm moving to Python) by masklinn on Monday November 29, 2010 @01:00PM (#1951118)
1. bar's visibility is package local, so your code is already broken, bar is invisible outside its package

2. let's say you solve this conundrum by making the field public

2.1. This piece of code is now frozen solid, you will not be able to ever refactor it (where refactoring is defined as changing implementation without changing behavior) since you can not transparently swap fields and methods in Java

2.2. This piece of code is dead to abstract types, as fields can not be part of interfaces in Java.

2.3. This piece of code is incompatible with Java Beans and will therefore be unusable in e.g. JSP taglibs

Re:Ruby is beautiful (but I'm moving to Python) by axod on Monday November 29, 2010 @01:45PM (#1951296)
JSP taglibs? wtf are you talking about. I'm in no way defending the idiocy of 'enterprise java'.

and your other points don't really make any sense at all. There is no such thing as 'fozen solid code'. Unless you're interfacing to external libraries etc and have agreed on a specific API, which is unlikely to include "yeah just reference 'bar' directly" unless you're insane.

Re:Ruby is beautiful (but I'm moving to Python) by nimms on Monday November 29, 2010 @02:05AM (#1949638)
until java has a var keyword and closures, there is no way you can claim that it's less verbose than languages like ruby or python.

I can't count the amount of time I wasted typing things like

  LongVariableName longVariableName = new LongVariableNameImpl();
as a java programmer. Also the amount of extra typing for creating anonymous inner classes made GUI coding a real chore. Sure your IDE can automate lots of it, but emacs automatically types end for me when I type def so it's not even a consideration.

Your comment comes across as someone who is either trolling or has no real experience in a language outside of java.

Re:Ruby is beautiful (but I'm moving to Python) by clyfe on Sunday November 28, 2010 @04:07PM (#1948304)
Ruby can use both "{...}" and "do ... end", with a slight difference between the two (precedence):

    def some_method { ... }
    def some_method; ... end

    obj.something # "something" is allways a method
    # never a var, say accessor (getter, setter &c ...)
Re:Ruby is beautiful (but I'm moving to Python) by axod on Sunday November 28, 2010 @04:15PM (#1948318)
Having optional beauty isn't really any beauty at all though.

I'm just more at home with exact, specific concise well structured syntax.

I know it's an extremely unpopular opinion to hold, especially round these parts, but I don't see any beauty in Ruby syntax. Same with Python...

Re:Ruby is beautiful (but I'm moving to Python) by steveklabnik on Sunday November 28, 2010 @04:10PM (#1948312)
def cannot have {}, it needs ;/end.

{} or do/end work for blocks, however.

Re:Ruby is beautiful (but I'm moving to Python) by clyfe on Sunday November 28, 2010 @04:17PM (#1948328)
indeed, you are right
Re:Ruby is beautiful (but I'm moving to Python) by nwmcsween on Monday November 29, 2010 @03:44AM (#1949792)
There's ways to make anything look hideous, as for your points. * end vs {} is one more character, I can't believe I even typed this as it's so stupidly pedantic. * Keywords.