"Try it yourself!" Why won't a {} one liner work?


#1


If I user a {} one liner to call my method I get an error, yet if I use do and end or break the curly braces into multiple lines it passes? I thought it was possible to use the curly braces all on one line?

def double(number)
    puts "Lets double some numbers!"
    yield(4)
    puts "Alright, let's do it again!"
    yield(number)
    puts "Okay, that's enough doubling for now!"
end

#this doesn't work
double(5) { |n| n*=2 puts "Here is your doubled number, #{n}!" } 

#but this does work
double(5) { |n| 
    n*=2
    puts "Here is your doubled number, #{n}!" 
}

#and this works also
double(5) do |n| 
    n*=2
    puts "Here is your doubled number, #{n}!" 
end


#2

Technically, you could put multiple lines all in a single {} one liner.
You just need to put a semi-colon ; for each command to separate them.


#3

Thank you for the reply! Semi-colon solved the issue!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.