r/ruby • • Aug 20 '24

The Rubyist journey

Post image
253 Upvotes

57 comments sorted by

105

u/anykeyh Aug 21 '24

And now (3.2+), embrace the laziness!

def adult? = age >= 18

29

u/nzifnab Aug 21 '24

I don'[t like this one-liner syntax personally

29

u/anykeyh Aug 21 '24

I do like, it works well with the new Data structure:

MyRecord = Data.define(:name, :status) do
  def done? = status == :done
  def in_progress? = %i[pending idle].include(status)
end

rec = MyRecord.new(name: "hello", status: :idle)
rec.in_progress? # true

Data is cool by the way, it's a Struct object which is frozen (read-only).

11

u/GozerDestructor Aug 21 '24

At least put a blank line after each method's definition. When I see "def", I naturally assume the line that follows is going to be part of the method - seeing another 'def' there is jarring.

Methods need to breathe, give them some space.

5

u/Kahlil_Cabron Aug 21 '24

This sucks ass to read. Also doing do and end in a one liner looks bad, conventionally curly braces are used for that.

12

u/wrestlethewalrus Aug 21 '24

This is a real chore to read for anyone who isn‘t doing it daily, and in a time where people are letting chatgpt write their code, readability is much more important than saving a few characters.

11

u/rco8786 Aug 21 '24

This is a strange criticism IMO. Any code is a chore to read if you're not doing it daily (at at least regularly). And not sure what to do with the chatgpt comment. Don't use it if it's producing bad code. It has no bearing on how humans should write code.

2

u/wrestlethewalrus Aug 22 '24

The point about chatgpt is that you‘re not going to be writing code much longer. Nobody cares if it‘s quick or slow to write.

But you need to understand what it does in order to check it, so all programming languages should be optimized for readability from now on, at least if they want to be successful.

1

u/rco8786 Aug 22 '24

chatgpt does not produce code that's particularly readable, which is why it's so important to optimize for readability?

I'm just not following. If chatgpt can't produce readable code, and we're not writing code ourselves, what should we be doing, exactly, to optimize for readability?

are you saying we need to make new programming languages that are optimized for chatgpt to produce readable code? where is the code going to come from to train chatgpt on these languages?

1

u/wrestlethewalrus Aug 25 '24

I hope you‘re close to retirement age.

6

u/Kushali Aug 21 '24

Disagree. I haven’t done Ruby as my full time job in 10 years and that was instantly readable to me. Also, cool.

1

u/anykeyh Aug 21 '24

I don't get why the hate. This is super useful in very niche uses, like this state example above, also when attr_accessor is not accessible (Think BasicObject inheritance):

class VeryBareMetalClass < BasicObject
  def initialize(x) = @x = x
  def x = @x # eq. attr_reader :x
end

Also when you want to create interface in Ruby (there is no interfaces in ruby):

class TemplateDesign
  def do_something
     #...
  end

  def result
     do_something
     result_impl
  end
protected
  def result_impl = raise NotImplementedError, "implement result_impl"
end

also when some features doesn't exists in your implementation:

class MongoDriver < DataDriver
  def transaction = yield # not supported in mongodb implementation
end

etc, etc... I don't think it's too difficult to read, and actually you can catch more informations. But that's my 2 cents.

3

u/FeetOfAChicken Aug 21 '24

That's really nice.

3

u/collimarco Aug 21 '24

I find it really hard to read compared to normal syntax

1

u/sintrastellar Aug 21 '24

What is this sorcery

3

u/2called_chaos Aug 21 '24

I'm torn, I like the idea but the syntax not so much. I find it useful in some circumstances, sure you could also use the verbose version but I do like the compactness sometimes. This is from a pet project which inherently is a bit messy and unoptimized but I kinda like the use of oneliners in the Collection class (the alignment might be a nogo for some) and the VoidEmblem class: https://gist.github.com/2called-chaos/8b625d0398a5b29d1fc32046123e2282

Especially for the latter, simple class overwrites/null object, I really kinda like it

5

u/anykeyh Aug 21 '24

Yeah that's a good example. What is bad is the inherit from array. This should use a délégation pattern instead.

Here, selector are going to create an unflavored array, the new constructor is going to copy the unflavored array into a new array. So that's a lot of memory allocation and temporary object created for each call.

Using delegator and an @array internal object would solve this.

It's a detail, but interesting to note.

1

u/2called_chaos Aug 21 '24

Hmm would this then still be chainable? Wouldn't I still need to create a new instance and passing the array for that to work or am I missing something? i.e. self.class.new(@array.sort_by{...})

I guess the point is that currently the array is created twice but with the delegation method the array created by e.g. sort_by could/would be passed as reference?

3

u/anykeyh Aug 21 '24

Yeah you would use:

self.class.new(@array.sort_by{...})

Look almost the same, but now the constructor is like this:

def initialize(arr)
  @array = array
end

So you will reference the array created by sort_by (one copy due to sort_by)

in current implementation, it will uses standard Array#new(array) method, which will copy as per reference here: https://ruby-doc.org/core-2.7.1/Array.html#method-c-new

So, using reference instead of inheritance in this case will reduce array copy from 2 (original -> sort_by -> new class inheriting from array) to 1 (original -> sort_by -> reference this array).

However, to be clear, it's not a big deal if array is small enough, and delegation can be a bit tedious to setup. Using method_missing might be actually slower at this JIT era.

I would validate the code as-is if it was coming from my team, unless I am aware that those array might handle thousands of elements and constructed/destroyed often in business code.

2

u/2called_chaos Aug 21 '24

Thanks for the explanation. Yeah that pet project is generally ludicrous, I pull and parse a 5MB JSON blob from the DB every request but it works surprisingly well for how crazy that is

3

u/poop-machine Aug 21 '24

It works well when you have to define a ton of similar-looking getters/predicates

def text?   = type.is_a?(String)
def number? = type.is_a?(Numeric)
def array?  = type.is_a?(Array)
...

1

u/frostymarvelous Aug 22 '24

endless functions syntax

24

u/pilaf Aug 21 '24

Let's not forget that Ruby understands semicolons too, so you may as well use them to hint the interpreter, and while we're at it let's put parens around those conditions and return values too so they don't feel so naked. Oh, and self. never hurts, use it at every chance to reduce ambiguity.

def isAdult()
     if (self.age >= 18);
          return(true);
     elsif (self.age < 18);
          return(false);
     end;
end;

I used 5 spaces for indentation too because 2 is kinda hard to read, and 4 is an unlucky number in Japanese (I don't want to be disrespectful to Matz).

2

u/nzifnab Aug 21 '24

Our linter would be having a field day lol

1

u/banana_in_the_dark Aug 21 '24

The if statement could be a little more specific. Check explicitly for self.age === 18 instead. Don’t forget the triple equals because self.age isn’t 18, it’s obviously just self.age

35

u/nateberkopec Puma maintainer Aug 21 '24

The meme is a bit weak, but the format has potential.

32

u/LordThunderDumper Aug 21 '24

Reddit.posts.current.images.reverse

Read that top to bottom and was wondering.

12

u/poop-machine Aug 21 '24
def adult?
  return false if age == 0
  return false if age == 1
  return false if age == 2
  return false if age == 3
  return false if age == 4
  ...
end

12

u/katafrakt Aug 21 '24
def adult?
  [21, 19, 18].include?(age)
  # we won't be using other adult ages during the hackathon demo
end

14

u/akira410 Aug 21 '24

Let's take it one more level:

def isAdult?(age)
  Proc.new {
    ->(a) {
      is_adult_proc = ->(val) {
        if val >= 18
          :adult
        else
          :not_adult
        end
      }
      is_adult_proc.call(a)
    }.call(age)
  }.call == :adult
end

Ugh... I feel so dirty.

11

u/anykeyh Aug 21 '24

If the goal is to make cursed code, I love this one:

def adult?
  Math.sqrt(age - 18) rescue false
end

I love it, because I saw too often real codes following this pattern ;-) Oh, it doesn't return true, it returns truthy value, for the sake of keeping it concise.

2

u/akira410 Aug 21 '24

Oh! I hate it and love it at the same time! That's a good one! Thank you for sharing it.

6

u/ric2b Aug 21 '24

I'm more excited about the template than this specific meme itself.

9

u/matheusrich Aug 21 '24
def isAdult()
    case @age
    when ...18 then
        return false
    when 18.. then
        return true
    end
end

3

u/mrfredngo Aug 21 '24

Don't quite understand... Shouldn't the direction be reversed? What am I missing?

1

u/jrhorn424 Aug 22 '24

I took the top image as "idiomatic ruby" and the last image as "barely resembles (a) ruby".

1

u/Periiz Aug 21 '24

No, but the last one is actually very smart. You see even without an else clause, this is always going to work because there is no number not greater than or equal to 18 nor less than 18!

/s

1

u/MeroRex Aug 21 '24 edited Aug 21 '24

def adult?(age)

return false unless (age / 18.0 ) < 1.0 ? false : true

return true

end

This is the only way.

-5

u/Kina_Kai Aug 21 '24

I don't know if the implicit return is always best. It is nice and there are times where it fits well, but I've grown to feel that it's better to be explicit in the general case.

14

u/ignurant Aug 21 '24

There’s a certain set of design decisions that this is part of that I’ve always admired. At first, the “implicit return” and “optional parenthesis” come off as a flourish akin to choosing to be different in some “look what I can do” kind of way. But as you follow the rabbit hole, you learn that these are sort of consequences of a fundamental design decision rather than a “look how punk rock we can be”.

I started to understand some of this while they were debating a potential |> function pipeline operator feature a few years ago. Matz made a comment regarding why we can’t capture a reference to a method as easily as in other languages. It was the first time I realized that while Ruby is quite similar to py and js, it is designed in a fundamentally different way that has real repercussions. And I started to appreciate how things like implicit return and no parens are side effects of that design, rather than just gimmicks.

I’ve come to think that this design constraint and these side effects are a large contributor to Ruby’s conversational nature.

In the end, for me, Ruby is about the “conversation between objects” rather than the “instructions to do something”.  This shows in the meme too. The versions descend into progressively more focus on “instructions”. When it’s about the conversation, return doesn’t even mean anything at all. Because of course sending a message to an object has a reply. Everything is an expression. 

Anyway, none of this is intended to reflect on you in particular, but your comment inspired me to get chatty.

1

u/Kahlil_Cabron Aug 21 '24

If you come from a functional programming background, implicit returns make a lot more sense. Some of the earliest programming languages only had implicit returns. It makes way more sense to me (though I like having explicit returns for early returning).

7

u/twinklehood Aug 21 '24

I hope we can at least agree that single line methods never need it?

2

u/tomc-01 Aug 21 '24

I suspect that agreement will only be after another 5 paragraphs of text discussing a single line method in ruby. 🤣

1

u/Kina_Kai Aug 21 '24

Hey, where’d that bikeshed come from?

2

u/Kinny93 Aug 21 '24

Explicit returns should only be used if you want to return early.

1

u/banana_in_the_dark Aug 21 '24

I just feel like implicit returns is a Ruby staple..

-2

u/BlueEyesWhiteSliver Aug 21 '24

I hate the last one. In more convoluted systems, it can become non-obvious of the refactor that’s possible.

0

u/[deleted] Aug 21 '24

[deleted]

9

u/Kinny93 Aug 21 '24

…but the first option is also the easiest to understand?

0

u/[deleted] Aug 21 '24

[deleted]

5

u/expatjake Aug 21 '24

I respectfully disagree. I’d say the first, most concise one, has least unnecessary fluff adding to the cognitive load. I expect that your criticism could be levelled at a bunch of other ruby code but I don’t think it applies here.

31

u/[deleted] Aug 21 '24

[removed] — view removed comment

30

u/ric2b Aug 21 '24

Ban this person and send them to r/node

5

u/sirion1987 Aug 21 '24

Agree 😂