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

Some interesting and useful syntax here! However...

I’m also partial to this trick for grabbing just the first element of an array.

  family, = socket.peeraddr
This is the sort of code that really turns me off when I'm digging through Ruby. It adds no clarity and actually looks like a typo. What's wrong with this?

  family = socket.peeraddr.first
It's much clearer what's going on.


It could be more readable if you use a placeholder variable

  family, _ = socket.peeraddr
Which is more clear to me, but maybe not as much as just using .first


(context: I'm the author)

I do agree with you, but through some failing of my own I still quite enjoy that trick. I included it to highlight the syntax, but I'll add a note saying it's maybe not the best idea to actually use it.


I often use it when I'm running through code in a console.

I put it in production code once, but removed it when I realised the "# This comma is important" comment was longer than just using `.first`


The

    first,_ = list
syntax also works when you're reading the two first items:

    first,second,_ = list


As does `first, second = list.first(2)`.


Right. I think it works better in Python — although I'm partial towards `[family] = socket.peeraddr` or adding parens as the comma is a bit hard to see — because it also asserts that the RHS is a single-item iterable (or however many items you have on the left-hand side:

    >>> [a] = range(1)
    >>> [a] = range(2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: too many values to unpack
and it works on any iterable (any object with #to_a in ruby).




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

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

Search: