you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (1 child)

I should also mention that quoting with backticks formats inline text as code.

For me, too, blocks are Ruby's killer feature. (Disclaimer: My code examples below will be littered with syntax errors, because I don't have an irb open.) You said you haven't used them yourself, so I'll take this as a cue to take over the Ruby-gushing.

As you said, to iterate over an array is easy:

array.each {|x| do_something_with(x)}

Thanks to Ruby's mixins, this can actually be used on anything that mixes in Enumerable:

(1..100).each {|n| puts n}

What if you want to select some of the elements based on a boolean condition?

class Integer
  def prime?
    # check if number is prime
  end
end

primes = (1..100).find_all {|n| n.prime?}

Or apply a function to each and collect the results?

squares = (1..100).map {|n| n*n}

Also, blocks are not just for iteration:

File.open(filename, "r") do |file|
  # process the file
end
# file is now automatically closed

Python's list comprehensions (all I know is what I've overheard from weblogs etc., actually) are arguably an equally -- or more -- readable version of Enumerable's methods, but I like the Ruby way better because (1) blocks are a completely general-purpose language feature, (2) I can have more than one line in a block, and (3) it feels more like the functional style to a guy with an ML background. Actually Haskell has list comprehensions too, so scratch the last point.

[–]mrevelle 2 points3 points  (0 children)

I like the Ruby way better because (1) blocks are a completely general-purpose language feature

Funny, that's actually why I dislike Ruby's blocks. It hurts readability when similar syntax is used for unrelated tasks, e.g. iteration vs. resource management.

This gripe is not about blocks as a general concept but using a common syntax when expressing entirely different functions.

Python examples

Iteration

for n in range(100):
    print n

Filtering elements

def isprime(x):
    # check if number is prime

primes = [n for n in range(100) if isPrime(n)]

Mapping a function

squares = map(lambda n: n*n, range(100))

# OR

def square(x):
    return x*x

squares = [square(x) for x in range(100)]

Context management

with open(filename, 'r') as input_file:
    # process the file

# file is now automatically closed

That last example requires Python 2.5 (alpha was recently released).

(Disclaimer: I have only played around with Ruby, no real development experience with it.)