gsub does not work with do/end block, only brackets

M

Michael Chow

puts "abcdefg".gsub(/abc/) do |x|
x.upcase
end

^This does not work. ArgumentError, it's expecting the second argument
that's required when a block is not provided.

puts "abcdefg".gsub(/abc/) { |x|
x.upcase
}

^This works.

Why??
 
R

Rick DeNatale

puts "abcdefg".gsub(/abc/) do |x|
x.upcase
end

^This does not work. ArgumentError, it's expecting the second argument
that's required when a block is not provided.

puts "abcdefg".gsub(/abc/) { |x|
x.upcase
}

^This works.

Why??

Because {} binds tighter than do end

puts "abcdefg".gsub(/abc/) do |x|
x.upcase
end

Is parsed as:
puts "abcdefg".gsub(/abc/) { |x|
x.upcase
}

^This works.

Why??

Because {} binds tighter than do end

(puts ("abcdefg".gsub(/abc/))) do |x|
x.upcase
end

Which means that the block is associated with the call to puts rather than gsub.

While

puts "abcdefg".gsub(/abc/) { |x|
x.upcase
\ }

Is parsed as

puts ("abcdefg".gsub(/abc/) { |x|
x.upcase
\ })
 
P

Paul McMahon

Braces have high precedence, do end has low precedence so with

puts "abcdefg".gsub(/abc/) do |x|
x.upcase
end

puts is being passed the block, whereas in

puts "abcdefg".gsub(/abc/) { |x|
x.upcase
}

gsub is being passed the block. If you want to use do end, you can do =

something like

puts("abcdefg".gsub(/abc/) do |x|
x.upcase
end)

or

s =3D "abcdefg".gsub(/abc/) do |x|
x.upcase
end
puts s
 
A

Alex Gutteridge

puts "abcdefg".gsub(/abc/) do |x|
x.upcase
end

^This does not work. ArgumentError, it's expecting the second argument
that's required when a block is not provided.

puts "abcdefg".gsub(/abc/) { |x|
x.upcase
}

^This works.

Why??

It interprets the block you are trying to give to 'gsub' as a block
argument to 'puts' instead. Brackets remove the ambiguity:

irb(main):008:0> "abc".gsub(/a/){|x| x.upcase}
=> "Abc"
irb(main):009:0> "abc".gsub(/a/) do |x| x.upcase end
=> "Abc"
irb(main):010:0> puts "abc".gsub(/a/){|x| x.upcase}
Abc
=> nil
irb(main):011:0> puts "abc".gsub(/a/) do |x| x.upcase end
ArgumentError: wrong number of arguments (1 for 2)
from (irb):11:in `gsub'
from (irb):11
irb(main):012:0> puts("abc".gsub(/a/) do |x| x.upcase end)
Abc
=> nil


Alex Gutteridge

Bioinformatics Center
Kyoto University
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top