HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyrailsMinor

How to write save block code like this more elegant in Ruby?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisblockmorerubylikewritesaveeleganthowcode

Problem

I have a class Creator which will execute a block code for a number of times. I'm not sure how to write this in a more elegant way in Ruby.

class Creator
    attr_accessor :block
    def self.create(&block)
        @block = block
        return self
    end

    def self.for(number)
        0.upto(number) {
            block.call
        }
    end
end


And this is how I call it which I want to stay like this.

Creator.create{ 
  SomeModel.create!(@attr)
}.for(30)

Solution

You want instance methods, not class methods. With the current code, you would get:

hello = Creator.create { puts "Hello" }
goodbye = Creator.create { puts "Goodbye" }
hello.for(1)   # Prints "Goodbye"


Assuming you don't want block to be changed afterwards, I would change attr_accessor to attr_reader. I don't see much reason to even expose a reader, though — it seems that doing so would only lead to mischief.

class Creator
  # For compatibility with the old API
  def self.create(&block)
    return self.new(&block)
  end

  def initialize(&block)
    @block = block
  end

  def for(number)
    number.times { @block.call }
  end
end


This is just a syntactic sugar wrapper for blocks. Perhaps a more generic name than Creator might be appropriate. It might also be simpler to call number.times { block.call } directly.

Standard indentation for Ruby is two spaces.

Code Snippets

hello = Creator.create { puts "Hello" }
goodbye = Creator.create { puts "Goodbye" }
hello.for(1)   # Prints "Goodbye"
class Creator
  # For compatibility with the old API
  def self.create(&block)
    return self.new(&block)
  end

  def initialize(&block)
    @block = block
  end

  def for(number)
    number.times { @block.call }
  end
end

Context

StackExchange Code Review Q#39166, answer score: 3

Revisions (0)

No revisions yet.