1

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

2
  • Note: Ruby is a case-sensitive language and capital letters have specific meaning in terms of syntax. Variables and method names should be lower-case letters. Capitals indicate constants of the form ClassName or CONSTANT_NAME. Commented Sep 26, 2020 at 1:32
  • 1
    OK I see. Thank you very much. Commented Sep 26, 2020 at 1:59

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But how can I change your code using block if I want both of the result like ["1", "2"] if I call fizzbuzz(2) and ["-1-", "-2-"] if I call fizzbuzz(2) {|item| "-#{item}-"}
Then you need a conditional map at the end. Wrap that in an if (block_given?).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.