質問

Here's what I'm trying

class Lorem

  def ipsum &block
    data = get_data
    data.each { |id| block.call dolor(id) } if block_given?
    data
  end

  def dolor id
    {dolor: id}
  end

  private

  def get_data
    [1, 2, 3] # some fake data
  end

end

stuff = []
panda = Lorem.new
panda.ipsum { |thing| stuff << thing }

puts stuff.inspect
# => [{dolor: 1}, {dolor: 2}, {dolor: 3}]

Code smell!

This block feels really gross. Specifically the line with block_given?. Is there a better way to write it?

def ipsum &block
  data = get_data
  data.each { |id| block.call dolor(id) } if block_given?
  data
end

Can i somehow use &method or some other magics?

役に立ちましたか?

解決

You can simplify slightly:

def ipsum
  data = get_data
  data.each { |id| yield dolor(id) } if block_given?
  data
end

Taking advantage of the fact that Array#each returns the array, this is arguably even simpler, but I'm not sure I like it:

def ipsum
  return get_data unless block_given?
  get_data.each { |id| yield dolor(id) }
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top