Keith Schacht’s Weblog

Subscribe
Atom feed for Ruby

4 items tagged “Ruby”

💡 TIL: Ruby’s clamp method reduces conditionals #

You can constrain a variable to be within a range using clamp:

5.clamp(1, 10)  # => 5
-3.clamp(1, 10) # => 1
15.clamp(1, 10) # => 10

💡 TIL: Regex within string square brackets #

I’ve always known that Ruby supports ranges within a string’s square brackets. So in addition to the simple `name[4]` I can do `name[2..4]` and `name[2...]` and `name[-1]`. But I just learned you can put regex in the square brackets for more dynamic substring selectors: `“me+abc123@email.com”[/.+\+(.+)@(.+)/, 2]` will give you the subdomain of the email address. It even works with named capture groups! `“123.45”[/(?<dollars>\d+)\.(?<centers>\d+)/, :dollars]` will give you the dollars. The article has a few other notable examples.

via

📝 Ruby Sorbet is too verbose, can the syntax be improved? #

Awhile back when I was ramping up on Typescript, I was leaning into the benefits of types. In the Ruby world, Sorbet is the most common way to add types so I gave that a shot. In the end, I ripped it out. I spent more time wrangling type checking then the time it spent catching bugs, and one of the issues was the verbose syntax. But recently I came up with a novel solution to this problem. First, here is the verbose syntax — you end up declaring all your arguments twice:

sig { params(name: T.untyped, nickname: String).returns(Integer) }
def greet(name, nickname)
  puts "Hello, #{name}! Your nickname: #{nickname}"
  name.length
end

Read more ▾

💡 TIL: Ruby can chain methods and right-assign #

I just learned that ruby supports re-writing this:

total = plus_shipping(with_taxes(subtotal(items)))

As:

subtotal(items).then { |subtotal| with_taxes(subtotal) }.then { |total| plus_shipping(total) } => total
from davetron