Forum: Ruby using n.times with gsub

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A2ac96168578a18921024b30825fa005?d=identicon&s=25 davidpthomas (Guest)
on 2005-11-15 03:45
(Received via mailing list)
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
10d4acbfdaccb4eee687a428ca00a5d8?d=identicon&s=25 jim (Guest)
on 2005-11-15 04:00
(Received via mailing list)
On Monday 14 November 2005 09:42 pm, davidpthomas@gmail.com wrote:
> 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 }
91ac0ea6ae5c8cd67e2ed455b43ffbee?d=identicon&s=25 sgentle (Guest)
on 2005-11-15 04:12
(Received via mailing list)
On 11/15/05, davidpthomas@gmail.com <davidpthomas@gmail.com> wrote:
> 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
1bac2e65d64faf472cf2ebc94f0f5ee0?d=identicon&s=25 ara.t.howard (Guest)
on 2005-11-15 04:15
(Received via mailing list)
On Tue, 15 Nov 2005 davidpthomas@gmail.com wrote:

> 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
E2b3bbf241a5daee3ee7696a7d4b2015?d=identicon&s=25 caldridge (Guest)
on 2005-11-15 04:18
(Received via mailing list)
"asdf".gsub(/^/," "*5)
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 dblack (Guest)
on 2005-11-15 04:27
(Received via mailing list)
Hi --

On Tue, 15 Nov 2005, Ara.T.Howard wrote:

>>
>  b
>       b
>       c

Tiny further simplification: s/<// :-)


David
04a56914cc09f0858d3fca2bf4cbde34?d=identicon&s=25 nobuyoshi.nakada (Guest)
on 2005-11-15 05:12
(Received via mailing list)
Hi,

At Tue, 15 Nov 2005 11:42:17 +0900,
davidpthomas@gmail.com wrote in [ruby-talk:165800]:
> GOAL: one-liner substitute of 5 spaces at beginning of a line.

ruby -pe 'print "     "' < foo.out
This topic is locked and can not be replied to.