using n.times with gsub

D

davidpthomas

GOAL: one-liner substitute of 5 spaces at beginning of a line.

WORKS: gsub(/^/, " ")
FAILS: gsub(/^/, 5.times {putc " "})

-example-
WORKS: $ cat foo.out | ruby -pe 'gsub(/^/, " ")'
FAILS: $ cat foo.out | ruby -pe 'gsub(/^/, 5.times{putc " "})'


I've tried variations of putc, puts, and print. All fail in different
ways.

thoughts? -- dave
 
J

Jim Weirich

GOAL: one-liner substitute of 5 spaces at beginning of a line.

WORKS: gsub(/^/, " ")
FAILS: gsub(/^/, 5.times {putc " "})

-example-
WORKS: $ cat foo.out | ruby -pe 'gsub(/^/, " ")'
FAILS: $ cat foo.out | ruby -pe 'gsub(/^/, 5.times{putc " "})'


I've tried variations of putc, puts, and print. All fail in different
ways.

cat foo.out | ruby -pe 'gsub(/^/, " " * 5)
cat foo.out | ruby -pe 'gsub(/^/, (1..5).collect { " " }.join }
 
A

Ara.T.Howard

GOAL: one-liner substitute of 5 spaces at beginning of a line.

WORKS: gsub(/^/, " ")
FAILS: gsub(/^/, 5.times {putc " "})

-example-
WORKS: $ cat foo.out | ruby -pe 'gsub(/^/, " ")'
FAILS: $ cat foo.out | ruby -pe 'gsub(/^/, 5.times{putc " "})'


I've tried variations of putc, puts, and print. All fail in different
ways.

thoughts? -- dave

works:

harp:~ > cat a
a
b
c
harp:~ > ruby -pe ' 5.times{ gsub /^/, 32.chr } ' < a
a
b
c

simpler:

harp:~ > ruby -pe ' sub /^/, 32.chr * 5' < a
a
b
c

cheers.

-a
--
===============================================================================
| ara [dot] t [dot] howard [at] gmail [dot] com
| all happiness comes from the desire for others to be happy. all misery
| comes from the desire for oneself to be happy.
| -- bodhicaryavatara
===============================================================================
 
S

Sam Gentle

WORKS: $ cat foo.out | ruby -pe 'gsub(/^/, " ")'
FAILS: $ cat foo.out | ruby -pe 'gsub(/^/, 5.times{putc " "})'

n.times returns n, so gsub, expecting a string instead of a number,
croaks at that.

I'm not sure if calling output functions inside a substitution is
something you really want to do... wouldn't something like Jim's
answer, or even " " * 5 make more sense?

Sam
 
D

David A. Black

Hi --

works:

harp:~ > cat a
a
b
c
harp:~ > ruby -pe ' 5.times{ gsub /^/, 32.chr } ' < a
a
b
c

simpler:

harp:~ > ruby -pe ' sub /^/, 32.chr * 5' < a
a
b
c

Tiny further simplification: s/<// :)


David
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top