r/ruby • • Jul 09 '23

So much knowledge in one joke

Post image
130 Upvotes

18 comments sorted by

33

u/IN-DI-SKU-TA-BELT Jul 09 '23
['1', '2', '3']

34

u/duongdominhchau Jul 09 '23

%w[1 2 3]

6

u/monstaber Jul 09 '23

*?1..?3

6

u/RiWo Jul 09 '23
'123'.chars

5

u/monstaber Jul 09 '23

321.digits.map &:to_s

0

u/[deleted] Jul 09 '23

[deleted] — view deleted comment

4

u/tinco Jul 09 '23

*?1..?3

I'm not sure, it doesn't work. I didn't know you could use question mark to get character literals so that's a TIL, but splatting a range like that doesn't work.

You could do this though: (?1..?3).to_a

Did reddit mangle the code? Maybe there's some other syntax feature I'm missing..

3

u/143Crimson Jul 09 '23 edited Jul 10 '23

It should instead have been [*?1..?3]

1

u/Comprehensive_War_99 Jul 11 '23

Old fashioned stuff. What about

p Enumerator.produce("1", &:succ).take(3)

9

u/[deleted] Jul 09 '23

Someone please benchmark these I need to know which is fastest

11

u/laerien Jul 09 '23
Calculating -------------------------------------
          &:to_s      3.807M (± 1.0%) i/s -     19.406M in   5.098169s
              _1      3.577M (± 1.4%) i/s -     18.055M in   5.049059s
               n      3.613M (± 0.8%) i/s -     18.262M in   5.055204s
            each      3.068M (± 0.8%) i/s -     15.342M in   5.001101s
             for      3.025M (± 0.7%) i/s -     15.259M in   5.045119s
           while      3.192M (± 0.8%) i/s -     16.003M in   5.013380s

Comparison:
          &:to_s:  3806841.0 i/s
               n:  3612769.0 i/s - 1.05x  slower
              _1:  3576545.7 i/s - 1.06x  slower
           while:  3192341.8 i/s - 1.19x  slower
            each:  3067873.6 i/s - 1.24x  slower
             for:  3024632.1 i/s - 1.26x  slower

3

u/laerien Jul 09 '23

For what it's worth, this microbenchmark is faster on JRuby and much faster on TruffleRuby.

1

u/[deleted] Jul 10 '23

Thank you for this! Is this summary for yjit??

1

u/laerien Jul 10 '23

Yes. I should have said, the above is Ruby 3.3.0-preview1 + YJIT.

1

u/kallebo1337 Jul 09 '23

3 down to one dot reverse

1

u/armahillo Jul 10 '23

why not 1 upto 3?

1

u/Practical_Ear_4307 Jul 10 '23

I use python now but I still miss ruby much

1

u/IN-DI-SKU-TA-BELT Jul 10 '23

We miss you too!

1

u/gxwho Aug 03 '23

3rd is php/js style 4th is c++ style