home.social

#rubytips — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #rubytips, aggregated by home.social.

  1. Master error handling in Ruby 🛠️
    Our latest guide breaks down try-catch and exception handling with clear examples.
    Read more 👉 railscarma.com/blog/ruby-try-catch-explained-exception-handling-in-ruby/
    #Ruby #ExceptionHandling #RailsCarma #RubyTips

  2. I've been copying a variation of this snippet into most Ruby projects:

    class BigDecimal
    def inspect
    "BigDecimal(\"#{to_s(?F)}\")"
    end
    end

    It overrides the default appearance of a BigDecimal in an irb/pry/rails console. Why?

    1. Easier to visually scan than exponential notation
    2. Can be copy-pasted to get another bigdecimal (otherwise using exp notation yields a Float instance)

    #ruby #rubytips

  3. If you wish to memoize (cache / calculate only once) a value, a Hash with a block in ruby is a good way to do it.

    For example:

    h = Hash.new do |hash, key|
    hash[key] = "Default value for #{key} "
    end

    h.fetch(:no_such, "not defined")
    #=> "not defined"

    h[:no_such]
    # => "Default value for no_such"

    This is means the value for h[:no_such] gets set the first time it is accessed and no longer needs to be calculated with the block, but fetch does not use that default proc.

    #Ruby #RubyTips

  4. When you use the block syntax with Hash.new to define a default value, you lock yourself to only using the square bracket syntax for value lookup. The fetch method ignores the block, default, and default_proc.

    This bit me hard this week, and my pair, @gd, got to watch me flounder on why fetch wasn’t getting the default value.

    By the way, the Hash.new with a block is great for memoization of calculated or network lookup data.

    #Ruby #RubyTips #RubyGotchas #ThisWeekILearned #TWIL

  5. OK experienced rubyists - putting your hindsight glasses on name 1 ruby topic or facet of ruby you wished you had studied more when you were getting started out with ruby.

    #rubytips