by torben-friis · 1y ago · 0 comments
let isLarge = a => a>100;
numbers.filter(isLarge)
Blocks let you do the same but without extracting the body as cleanly. Maybe it’s a chronological issue, where Ruby was born at a time when the above wasn’t commonplace?
>When you write 5.times { puts “Hello” }, you don’t think “I’m calling the times method and passing it a block.” You think “I’m doing something 5 times.”
I’m of two minds about this.
On the one hand, I do agree that aesthetically Ruby looks very clean and pleasing. On the other, I always feel like the mental model I have about a language is usually “dirtied” to improve syntax.
The value 5 having a method, and that method being an iterator for its value, is kinda weird in any design sense and doesn’t seem to fix any architectural order you might expect, it’s just there because the “hack” results in pretty text when used.
These magical tricks are everywhere in the language with missing_method and the like, and I guess there’s a divide between programmers’ minds when some go “oh that’s nice” and don’t care how the magic is done, and others are naturally irked by the “clever twists”.
I don't think this is particularly weird, in Ruby at least. The language follows object orientation to its natural conclusion, which is that everything is an object, always. There is no such thing as "just data" in Ruby, because everything is an object. Even things that would just be an `int` in most other languages are actually objects, and so they have methods. The `times` method exists on the Integer classes because doing something exactly an integer number of times happens a lot in practice.
The issue is more with this part:
>The `times` method exists on the Integer classes because doing something exactly an integer number of times happens a lot in practice.
It is practical, but it breaks the conceptual model in that it is a hard sell that “times” is a property over the “5” object.
The result is cleaner syntax, I know, but there is something in these choices that still feels continually “hacky/irky” to me.
process.start() is the action of starting done by the the noun that is the process.
It's not exactly a matter of naming, as some methods are not explicitly verbs, but there is almost always an implicit action there: word.to_string() clearly has the convert/transform implication, even if ommitted for brevity.
I see no path where 5 is a noun and times the verb, nor any verb I can put there that makes it make sense. If you try to stick a verb (iterate?) it becomes clear that 5 is not the noun, the thing performing the iteration, but a complement - X iterates (5 times). Perhaps the block itself having a times object with 5 as an input would make it more standard to me (?).
But I do understand that if something is extremely practical a purist/conceptual argument doesn't go very far.
Maybe here is the confusion, ruby is based on message passing, so the `times` is a message you are sending to 5, not a property of it.
When you learn the language you really fall into two camps:
- ah, yes, this is unusual, but it's consistent and now i understand the language
- this is way too clever
I'm more in the first camp.
But blocks are not objects in Ruby, so you can’t do that, and everything actually isn’t an object in Ruby.
Also, it’s even more common to do something depending on whether a condition is true or false, but true and false in Ruby don’t have a method to (not) execute a block on them, and you use a non-OOP `if` instead, so what’s up with that?
I beg to differ. What object does the method `puts` belong to? Why do you not call puts with its objects name?
Ruby has a concept of mixins (Golang interfaces), these are not objects. Neither is `puts`
Ruby "mixins" are the affordance of sharing instance methods from a module via a keyword. Modules are objects, and are instances of class Module:
module ProvidesFooMixin
def foo = "foo"
end
class Bar
include ProvidesFooMixin
end
Bar.new.foo
# => "foo"
puts(ProvidesFooMixin.class)
# => Module
ProvidesFooMixin.object_id
# => (some integer value)
>Neither is `puts`Like all methods, `puts` is an object:
method(:puts)
# => #<Method: Object(Kernel)#puts(*)>
method(:puts).class
# => Method
method(:puts).object_id
# => (some integer value)
Here you see evidence of where `puts` comes from: Kernel#puts via Object, which I will now explain in detail.>What object does the method `puts` belong to?
It belongs to the object you are calling it from within. You don't need to call `puts` with a receiver because it is an instance method, just like you don't need to call an instance method `foo` via `self.foo`. But you could choose to use a receiver, since the `puts` you know and love is just another instance method. You can try `self.puts` for yourself in some context!
Your classes (and their instances) inherit this `self.puts` instance method from the Object class, which includes the Kernel module, which provides `Kernel#puts`. So the only reason you can send it as a message without a receiver is because it is just another instance method (again, the same as calling instance method `#foo` without using `self.foo`).
Caveat: You can build an "alternate universe" object hierarchy by inheriting from BasicObject, and in your alternate universe, you can choose to not `include Kernel`, and you will see that instances of your new objects do not have access to `puts` in their instance scope.
Mixins are just modules, which are objects, which you can call methods on. (Or rather, send messages to) You can easily verify this in irb calling a method on (for example) the Enumerable module:
irb(main):001> Enumerable.class
=> Module
You are right that a module is not a class, and it is not possible to call `.new` on it. But the module itself is very much an object.puts is a method which has a class: the Method class:
irb(main):001:0> method(:puts)
=> #<Method: main.puts>
irb(main):002:0> method(:puts).class
=> Method
Everything being a confused muddle in Ruby, there is evidently some Kernel base class that is injected into every Object, and puts is a private method in that: irb(main):003:0> 3.puts()
Traceback (most recent call last):
2: from /usr/bin/irb:11:in `<main>'
1: from (irb):3
NoMethodError (private method `puts' called for 3:Integer)
The Method class of puts is a real class with methods and all: irb(main):004:0> method(:puts).class.methods
=> [:allocate, :superclass, :<=>, :<=, :>=, :==, :===, :autoload?, :autoload, :included_modules, :include?, :name, :ancestors, :attr, :attr_reader, :attr_writer, :attr_accessor, :instance_methods, :public_instance_methods, :protected_instance_methods, :private_instance_methods, :constants, :const_get, :const_set, :const_defined?, :class_variables, :remove_class_variable, :class_variable_get, :class_variable_set, :class_variable_defined?, :public_constant, :freeze, :inspect, :deprecate_constant, :private_constant, :const_missing, :singleton_class?, :prepend, :class_exec, :module_eval, :class_eval, :include, :<, :>, :remove_method, :undef_method, :alias_method, :protected_method_defined?, :module_exec, :method_defined?, :public_method_defined?, :to_s, :public_class_method, :public_instance_method, :define_method, :private_method_defined?, :private_class_method, :instance_method, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :instance_variables, :method, :public_method, :singleton_method, :define_singleton_method, :public_send, :extend, :to_enum, :enum_for, :pp, :=~, :!~, :eql?, :respond_to?, :object_id, :send, :display, :nil?, :hash, :class, :singleton_class, :clone, :dup, :itself, :yield_self, :taint, :tainted?, :untrust, :untaint, :trust, :untrusted?, :methods, :frozen?, :protected_methods, :singleton_methods, :public_methods, :private_methods, :!, :equal?, :instance_eval, :instance_exec, :!=, :__send__, :__id__]It really isn’t a confused muddle, the rules are very clear. Just because it doesn’t match what you expect from your other language experience doesn’t mean it isn’t clear.
The Kernel module is included in the Object class, which means its methods are available to every Ruby object and can be accessed from virtually any scope, including the top-level (global) context where self is an instance of Object called "main."
In the first place, I'd say what you're asking for goes beyond "everything is an object".
But I think your questions can be answered in a way that affirms that "everything is an object" in Ruby anyway.
> Why do you not call puts with its objects name?
Because it belongs to whatever object you're working in already; `puts` is identical to `self.puts`. And yes, you're always working in an object: https://bparanj.gitbooks.io/ruby-basics/content/chapter1.htm...
> What object does the method `puts` belong to?
As indicated above, it belongs to the object `self`. It gets added object via the mixing-in Kernel module into Object. Kernel is itself an instance of class Module: https://docs.ruby-lang.org/en/3.4/Module.html
The `puts` in Kernel delegates to `puts` from IO, which is likewise an instance method belonging to the object you can refer to by the name `$stdout`: https://docs.ruby-lang.org/en/3.4/IO.html
> Ruby has a concept of mixins [and], these are not objects.
Sure they are. Mixins themselves inherit from Module, and Modules are also objects (just like classes are).
Some highlights from Chapter 27 ("Library Reference: The Class Model") of the recent edition of the pickaxe book (emphasis mine):
> The Kernel module is included by class Object, so its methods are available in every Ruby object. One of the reasons for the Kernel module is to allow methods like `puts` and `gets` to be available everywhere and even to look like global commands. Kernel methods allow Ruby to still maintain an "everything is an object semantics".
and regarding mixins:
> The Module class is the class of any module you declare with the `module` keyword. Each module is an instance of class Module.
on Object:
> Object is the parent class of (almost) all classes in Ruby unless a class explicitly inherits from. BasicObject. [...] Object mixes in the Kernel module, making the built-in functions globally accessible.
tl;dr: mixins in Ruby are instances of class Module, and their methods end up bound to instances of class Object. Abstract module methods that don't belong to a concrete instance of some class that mixed in their module belong to the Object that is the module itself (the instance of class Module). (The same kind of thing is how class methods work.)
The `5.days` example that was posted somewhere else in this thread might be a better example. It is not, as far as I can tell, part of Ruby's core library, thank goodness, but it is the kind of thing the methods-as-hacks-for-syntax culture seems to encourage. My question being "why the heck should the number 5 know anything about days? What does 5.days even mean, given that there are various ways to interpret 'a day'?"
This kind of bad design has made its way all over the place. The Java mocking libraries that my coworkers like to use are full of it. Long chains of method calls that appear like they're trying to 'look like English' but make no damn sense, so you have to dig into each method call and what kind of thing it returns to understand what this chain actually means.
This adds some complexity in the language, but it means that it’s far more expressive. In Ruby you can with nothing but Array#each write idiomatic code which reads very similar to other traditional languages with loops and statements.
This can sometimes be useful: A calling method can pass down a block or proc to control if/when it wants an early return.
Basically Ruby has two types of closures:
* A return in a lambda returns to the calling scope. So basically, it returns to after where the "call" method is invoked.
* A return in a block or a proc returns from the scope in which it was defined (this is also why you get LocalJumpError if you try to return a block or a proc, but not a lambda to the method calling the one where the block or proc is defined).
When you name a block, you get a Proc object, same as you get when you take the value of a lambda or proc.
In practice, that blocks in MRI are not Proc objects already is just an implementation detail/optimisation. I have a long-standing hobby project to write a Ruby compiler, and there a "proc" and a bare block are implemented identically in the backend.
def foo
p 1
yield
p 2
end
foo { break }
This only prints "1" because the break stops the execution of the invoked method (foo). class TrueClass
def if = true
def ifTrue = true
end
class FalseClass
def if = false
def ifTrue = false
end
true.if
# => true
false.if
# => false (a > b) ifTrue: [ "do something" ]
EDIT: to clarify what's happening there, `>` is a message sent to `a` that will result in a boolean. The True class and False class both understand the ifTrue: message and `True>>ifTrue:` executes the block whereas `False>>ifTrue:` just throws it away.There's no `if` keyword in the language. Control flow is done purely through polymorphism.
isLarge = -> {|a| a > 100 }
numbers.filter(&isLarge)
Or you could replace the first line: isLarge = -> { _1 > 100 }
Some people hate that syntax, though. I think for trivial predicates like this, it's fine.E.g. 3:
(f, x) => f(f(f(x)))
let isLarge = a => a>100;
as a lambda and call via #call or the shorthand syntax .(): is_large = ->(a) { a > 100 }
is_large.call(1000)
# => true
is_large.(1000)
# => true
I find the .() syntax a bit odd, so I prefer #call, but that's a personal choice. Either way, it mixes-and-matches nicely with any class that has a #call method, and so it allows nice polymorphic mixtures of lambdas and of objects/instances that have a method named 'call'. Also very useful for injecting behavior (and mocking behavior in tests).Additionally, you can even take a reference to a method off of an object, and pass them around as though they are a callable lambda/block:
class Foo
def bar = 'baz'
end
foo_instance = Foo.new
callable_bar = foo_instance.method(:bar)
callable_bar.call
# => 'baz'
This ability to pull a method off is useful because any method which receives block can also take a "method object" and be passed to any block-receiving method via the "block operator" of '&' (example here is passing an object's method to Array#map as a block): class UpcaseCertainLetters
def initialize(letters_to_upcase)
@letters_to_upcase = letters_to_upcase
end
def format(str)
str.chars.map do |char|
@letters_to_upcase.include?(char) ? char.upcase : char
end.join
end
end
upcase_vowels = UpcaseCertainLetters.new("aeiuo").method(:format)
['foo', 'bar', 'baz'].map(&upcase_vowels)
# => ['fOO', 'bAr', 'bAz']
This '&' operator is the same as the one that lets you call instance methods by converting a symbol of a method name into a block for an instance method on an object: (0..10).map(&:even?)
# => [true, false, true, false, true, false, true, false, true, false, true]
And doing similar, but with a lambda: is_div_five = ->(num) { num % 5 == 0 }
(0..10).map(&is_div_five)
# => [true, false, false, false, false, true, false, false, false, false, true]In your experience, is it ok to use Procs for example for extraction of block methods for cleanliness in refactors? or would I hit any major roadblocks if I treated them too much like first-class functions?
Also, is there any particular Rails convention to place collections of useful procs? Or does that go a bit against the general model?
In addition to the efficiency issues of unnecessarily reifying blocks into Proc objects, there are some sharp edges that can cut you doing this. For instance, Ruby blocks and procs [0] have return semantics based on where they are defined (specifically, "return" in a block or proc returns from the method in which the block/proc is defined.) So if you have two identical blocks used in two different methods, and those blocks have return calls, and you refactor them to shared Proc defined somewhere else that is used in each method, you will find that the behavior is broken, and when it returns it will either return from the wrong method or produce a LocalJumpError, depending on the exact structure of the program.
Local return from a block/proc is done with "next" instead of "return" (and if neither a next or return is hit, the last expression evaluated will be treated as an implicit "next"), so a block without an explicit return can be converted to a proc and reused in different places more safely.
[0] using the convention of lowercase "proc" to refer to a Proc object that does not have lambda semantics, whereas those created with Kernel#lambdda or the stabby-lambda syntax are "lambdas".
Pass the wrong number of of arguments to a Proc or block, it will pass nil for missing args and omit extras. Pass the wrong number of arguments for a method or lambda and you get an ArgumentError. Use the return keyword in a lambda, it returns from the lambda, just like if you call return in a method. In a block or Proc, it returns from the calling method.
So I would feel comfortable leaning on them for refactoring as it's as Ruby intended. Just use lambdas when you want to turn methods into objects and Procs when you want to objectify blocks.
You should get ahold of a copy of Metaprogramming Ruby 2 if you find yourself refactoring a lot of Ruby. It's out of print, but ebooks are available.
So just be clear about whether you're talking about a proc or a Proc...
> In a block or Proc, it returns from the calling method
No, in block or a Proc it returns from the scope where it was defined.
Usually this is the same, and so it doesn't usually matter much, but if you pass a proc or a block down to another method, then a return within the block will still return from the method where it was defined.
This can occasionally be useful, as you can use it to pass in a predicate to a method that can control if/when you want to return, irrespective of how deeply nested.
In a block or proc, it returns from the method in which the block/proc was defined, not the calling method. These may or may not be the same; the proc may be called deeper in the call chain, or it might (erroneously) be called after the defining method had exited, producing a LocalJumpError.
This also means that implicit returns from a block/proc have different semantics than explicit returns, unlike lambdas/methods where implicit returns have the same semantics as explicit returns. (From a block/proc, the last evaluated expressions behaves as if it were passed to "next" rather than "return", resulting in a local return to the calling method rather than a return from the defining method.)
It's called the "callable" pattern.
>is it ok to use Procs for example for extraction of block methods for cleanliness in refactors?
As others have said, use Lambdas via `->() { do_thing }` over Procs if you want to pass them around. They are the "true" way to use first-class functions.
Also, if you want to pass methods around, you can do so, just be aware that they carry everything you might expect with them: they are called with the receiver still being the object they came from. Callbacks are uncommon in Ruby, but I've seen a few instances of passing methods of the current object into some other as a callback, e.g.
some_interactor.do_complex_thing(
order_id: 123,
on_success: method(:succeeded),
on_failure: method(:failed),
)
Then #do_complex_thing can use `on_success.call` and `on_failure.call`, which is nice when you want to stub these in unit tests without resorting to stubbing/mocking. You can just pass lambdas (first-class functions) as the value for :on_success and :on_failure kwargs in tests.>Also, is there any particular Rails convention to place collections of useful procs?
No convention for a "place" for these. I generally dislike how Rails got people into using directory names for the "kind" of a module/class instead of actually mirroring the architecture. This is kind of why.
If what you really desire is a big bag of pure functions in the global scope, you should still at least put them inside of a namespace (a Ruby module). For example, if you wanted a big bag of type coercions, you might put them into a module:
module CommonCoercions
class << self
def currency
->(value) { do_things }
end
def coordinates
->(value) { do_things }
end
end
end
However, this isn't necessarily very efficient. Each call to CommonCoercions.currency is going to instantiate a new Lambda instance! You could alleviate this by caching the value in a singleton-scope instance variable: module CommonCoercions
class << self
def currency
@currency ||= ->(value) { do_things }
end
def coordinates
@coordinates ||= ->(value) { do_things }
end
end
end
Even then, this isn't really common in Ruby. You might as well just have these be singleton methods outright (aka "class methods"): module CommonCoercions
class << self
def currency(value)
do_things
end
def coordinates(value)
do_things
end
end
end
If you really want to pass them around as first-class functions, you can grab a reference to that function like so: CommonCoercions.method(:currency)
And then use them via `.call()` the same as any other lambda if you want to pass them around.However, if you want to use them only locally within a particular class, in a Rails project you are better off just calling them directly on the module, or even delegating so that the method is available in the class as though it were a local instance method:
module CommonCoercions
def self.coerce_currency(value)
do_things
end
end
class SomeAction
delegate :coerce_currency, to: CommonCoercions
def some_method(params)
coerce_currency(params.fetch(:amount))
end
end