Sun Hao Lun
Sun Hao Lun

Reputation: 313

Ruby: Iterate the result from method using block

Now I have a ruby like this:

def fizzbuzz(numSize)
    result = []
    1.upto(numSize) do |num|
        if num % 15 == 0
            result << "FizzBuzz"
        elsif num % 3 == 0
            result << "Fizz"
        elsif num % 5 == 0
            result << "Buzz"
        else
            result << num.to_s
        end
    end
    result
end

print fizzbuzz(10) {|item| "-#{i1tem}-"}

If I want to print the result like this: ["-1-", "-2-", "-Fizz-", "-4-", "-Buzz-", "-Fizz-", "-7-", "-8-", "-Fizz-", "-Buzz-"]

What can I modify my code in method fizzbuzz if I can not change the code:

print fizzbuzz(10) {|item| "-#{i1tem}-"}

Thanks

Upvotes: 1

Views: 72

Answers (1)

tadman
tadman

Reputation: 211560

That block is being given to your method, but you're not making use of it. That's an easy fix:

def fizzbuzz(numSize, &block)
  # ... (existing code) ...
  result.map(&block)
end

Where that transforms the result value using map.

Note this requires fixing the typo in your print block which is i1tem not item.

It's also worth noting you should avoid this pattern:

x = [ ]
y.each do |v|
  x << f(v)
end
x

That's just a long-winded version of this:

y.map do |v|
  f(v)
end

Where when you're transforming on a 1:1 basis from the source just use map.

In your case that reduces the code to this more minimal form that has a lot less repetition:

def fizzbuzz(numSize, &block)
  1.upto(numSize).map do |num|
    if num % 15 == 0
      "FizzBuzz"
    elsif num % 3 == 0
      "Fizz"
    elsif num % 5 == 0
      "Buzz"
    else
      num.to_s
    end
  end.map(&block)
end

Upvotes: 1

Related Questions