Options Hashes Exercises

Hi, I’m stuck on an error returned by using n.times method, as it would return n instead of the string
3.times {print string} return 3 instead of the string
My method below:
def transmogrify(str, options = {})
defaults = {:times => 1, :upcase => false, :reverse => false}
options = defaults.merge(options)
new_str = str
new_str = str.upcase if options[:upcase] == true
new_str = new_str.reverse if options[:reverse] == true
options[:times].times {new_str}
end

so i changed the last line to new_str * options[:times] and i worked, but why wouldn’t n.times method work here?

Failures:

  1. #transmogrify should override the defaults when specified in the options hash
    Failure/Error: expect(transmogrify("foo ", options)).to eq(’ OOF OOF OOF’)

    expected: " OOF OOF OOF"
    got: 3

    (compared using ==)

    ./spec/00_options_hashes_spec.rb:11:in `block (2 levels) in <top (required)>’

That’s just how the .times method works. If you run n.times { . . . }, Ruby evaluates the code inside of the block n many times and then returns n. Similarly, if you run array.each { . . . }, Ruby evaluates the code inside of the block for each element of array and then it returns array. It’s just something to keep in mind.

1 Like