Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I agree with almost everything except for using named groups over the $1-$9 variables in regular expression matching. This may be the case if there are many capture groups in the expression, but I would argue that

    /(?<meaningful_var>regexp)/ =~ string
is a fair deal more difficult to read than simply

    /(regexp)/ =~ string
Almost everybody familiar with PCRE will be familiar with the simpler form, and it's usually the case that the shorter the regular expression, the easier it is to understand and read.


The following are equivalent:

  if /(?<meaningful_var>regexp)/ =~ string
    puts meaningful_var
  end

  if /(regexp)/ =~ string
    puts $1
  end
This may not look like much, but bare in mind you may be using the current selection in several places, at which point you'll probably use the following for readability either way:

  meaningful_var = $1
In any case I think that sometimes the latter is preferable, that's why I'm not into these kind of black and white conventions. OMG, this line is 85 characters, you suck.


It is true that one will probably immediately reassign the $- variables. And that's definitely true that there are cases when conventions impede good style. I would probably say, though, that in most cases the latter of your examples is preferable.

    if string =~ /First: (.*?) Last: (.*?)\s/
      first_name = $1
      last_name = $2
      # etc...
    end
looks far better to me than

    if string =~ /First: (?<first_name>.*?) Last: (?<last_name>.*?)\s/
      # etc...
    end


I think it's good to name these variables, obviously you need to use short names, otherwise you'll get very long regexps. but in any case it will increase readability imho.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: