2

I saw an intriguing answer to a simple question.

The question was: "Get the average of the ASCII values of each character in a string read from gets"

One of the correct answer was: p gets.sum/~/$/

I searched Google but couldn't find any explanation for this syntax. Any insights are welcome. Thanks.

frank
  • 295
  • 3
  • 8
  • This code looks very much like [Code Golf](https://codegolf.stackexchange.com/). While this is a great hobby and a good way to lean more about a language, you should make sure to not use those clever one-liners in actual production code. In real programs which are intended to be maintained for some time, aim for code which is boring, readable, and understandable instead of "clever". – Holger Just Aug 04 '17 at 22:32
  • @HolgerJust I would argue that those exact things make it a very poor way to learn more about a language. – Mark Thomas Aug 04 '17 at 23:25
  • 1
    @MarkThomas Well, it's not that you should use these one-liners exactly as you write them. But by trying to understand how they work (or even writing them yourself), you can gain a deep understanding about the syntactic and semantic details of a language. And this helps you later to detect and avoid potential issues in your production code you might not even notice without such a detailed understanding. You are absolutely right though in that code golf is usually not a great way to get a *basic* understanding of a language or to learn common and accepted idioms. It's still fun though :) – Holger Just Aug 05 '17 at 12:25

1 Answers1

4

We have a couple things going on here

  1. gets.sum is just calling sum on the string input by gets and is returning an integer.

The result is simply the sum of the binary value of each byte in str...

  1. /$/ is just a Regexp looking for where the end of the line is
  2. The ~ operator on a Regexp tells it to operate on the $_ global variable which is the last string input to gets or readline. In short this returns the index of the end of the line

Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

  1. Finally, tying these 2 together, we have a / which is just a division operator operating on 2 Integers.

It could have also been written using some spaces to make things more clear

p gets.sum / ~/$/

Note: If this was an average, they added in the value for \n but then didn't divide it back out:

gets.sum/~/$/
# Hello
# => 102
"Hello".sum / "Hello".length
# => 100
"Hello\n".sum / "Hello".length
# => 102
"Hello\n".sum / "Hello\n".length
# => 85
Simple Lime
  • 10,790
  • 2
  • 17
  • 32