3 ms·
x.succ is not the Ruby equivalent of ++$x in PHP (or Perl). x.succ returns x + 1 (by default, on integers) but does not increment x as ++$x does (since numbers
by petercooper 15y ago
x.succ is not the Ruby equivalent of ++$x in PHP (or Perl). x.succ returns x + 1 (by default, on integers) but does not increment x as ++$x does (since numbers are immutable and that's what "x" is giving us in Ruby). The closest match would be x += 1 (shorthand for x = x + 1). I don't see x = x.succ in common usage but that would work too.
- gb 15y agoI don't disagree with what you're saying, but it does mention in the comment that x is not mutated.
- petercooper 15y agoI totally didn't notice that note but the page doesn't seem to have been updated since then :-) I still don't see why it doesn't just use the common syntax though that does the same thing. It's intriguing that the Python one has no example for that row. Perhaps they are specifically looking for idiomatic techniques, even if they're not commonly used. I note that the page is on a wiki so I could fix it, but given it's been there for years, I suspect there's a good reason no-one has already made the change.
- adyus 15y agoAs a Ruby noob and without researching too much, here's my question: would x.succ! do it?
- petercooper 15y agoNot if x were a regular old Fixnum. The reason is that x would be referring to a number like 1, 42, or whatever, and numbers are immutable in Ruby. You can't "change" a number in-place. If you could change Ruby's concept of 1 into 2, then 1 would cease to exist and that would be a Bad Thing™ :-)
- jfarmer 15y agoYeah, #succ is something else. For example, if your object supports #succ then you can use it in ranges. e.g., (1..10), but also ("apple".."kiwis") or ('A'..'Z'). In this case, String#succ returns a string with the last alphanumeric character transformed into its successor, e.g., "apple".succ == "applef". The only time I've used it is implementing the range interface; I've never called it directly, let alone to increment an integer.
- neutronicus 15y agoI assume you mean "apple".succ == "applf" ?
- jfarmer 15y agoYes