简体   繁体   中英

can't pass block to Kernel sub method in Ruby

I'm trying to run a ruby one-liner in bash, and this is what happens:

~$ echo a$'\n'b$'\n'c | ruby -pe 'sub(/./,"x")'
x
x
x
~$ echo a$'\n'b$'\n'c | ruby -pe '$_.sub!(/./){"x"}'
x
x
x
~$ echo a$'\n'b$'\n'c | ruby -pe 'sub(/./){"x"}'
-e:1:in `sub': wrong number of arguments (1 for 1..2) (ArgumentError)
        from -e:1:in `sub'
        from -e:1:in `<main>'

Why doesn't command #3 work exactly like command #2?

(This is ruby 1.9.2. The echo statement is there only to provide three lines of input)

It looks like this was a bug in 1.9.2 . It was fixed for 2.0.0 (and backported to 1.9.3 ). The fix is simply to upgrade to a more recent version of Ruby.

You should probably upgrade if you can anyway, since support for 1.9.2 has just ended .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM