Forum: Ruby strings and ruby style?

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.
2a0f7bd2c54fbc44329d69555b96f1c5?d=identicon&s=25 Kev Jackson (Guest)
on 2006-03-29 06:36
(Received via mailing list)
Which of the following is considered better style?

$ie.text_field(args[0],
$test_data[args[1].to_s]["#{args[2]}_fld"]).value=$test_data[args[1].to_s][args[2].to_s]

$ie.text_field(args[0],
$test_data["#{args[1]}"]["#{args[2]}_fld"]).value=$test_data["#{args[1]}"]["#{args[2]}"]

ie is it better to use args[1].to_s or "#{args[1]}"

My current thinking is that "#{}" should be used when concatenating
strings together with values (or interpolating), where as .to_s should
be used when you want the string representation of an object.

Thanks
Kev

PS - I managed to get rid of all the evals hooray for me!
Bd0203dc8478deb969d72f52e741bd4f?d=identicon&s=25 Daniel Baird (Guest)
on 2006-03-29 06:49
(Received via mailing list)
To my (newbish) eye, it looks crazy to put a single #{} in a string like
this "#{args[1]}".  It looks less crazy to do it when you actually have
some
literal string content in there as well, like this "#{args[2]}_fld".

So I guess I'm voting for example one.

;Daniel (no, not *that* Daniel)



On 29/03/06, Kev Jackson <kevin.jackson@it.fts-vn.com> wrote:
>
>
>


--
Daniel Baird
http://danielbaird.com (TiddlyW;nks! :: Whiteboard Koala :: Blog ::
Things
That Suck)
[[My webhost uptime is ~ 92%.. if no answer pls call again later!]]
68db3bafb0a990bf605c4cf62bf85db0?d=identicon&s=25 Bret Pettichord (Guest)
on 2006-03-29 07:34
(Received via mailing list)
I like your "current thinking". I also think that the code is easier to
read if it consistently uses either one approach or the other. This
rule itself ends up favoring your second example over the first.

Bret

====

$ie.text_field(args[0],
$test_data[args[1].to_s]["#{args[2]}_fld"]).value=$test_data[args[1].to_s][args[2].to_s]

$ie.text_field(args[0],
$test_data["#{args[1]}"]["#{args[2]}_fld"]).value=$test_data["#{args[1]}"]["#{args[2]}"]
0b561a629b87f0bbf71b45ee5a48febb?d=identicon&s=25 Dave Burt (Guest)
on 2006-03-29 09:44
(Received via mailing list)
Kev Jackson wrote:
> PS - I managed to get rid of all the evals hooray for me!

Good work, now just get rid of those "#{fully interpolated}" strings and
extraneous to_s :)

> Which of the following is considered better style?
>
> $ie.text_field(args[0],
> $test_data[args[1].to_s]["#{args[2]}_fld"]).value=$test_data[args[1].to_s][args[2].to_s]
>
> $ie.text_field(args[0],
> $test_data["#{args[1]}"]["#{args[2]}_fld"]).value=$test_data["#{args[1]}"]["#{args[2]}"]

It's nice to fit a line on one line. How's this?

  test = $test_data[args[1]]
  $ie.text_field(args[0], test[args[2] + "_fld"]).value = test[args[2]]

> ie is it better to use args[1].to_s or "#{args[1]}"

to_s, but if you control your $test_data and args, and can't imagine how
args[1] or args[2] could be anything other than strings, there's no need
for
a cast at all.

> My current thinking is that "#{}" should be used when concatenating
> strings together with values (or interpolating), where as .to_s should be
> used when you want the string representation of an object.

I don't like using interpolation when the stuff I'm interpolating is
bigger
than the literal part of the string.

Cheers,
Dave
2a0f7bd2c54fbc44329d69555b96f1c5?d=identicon&s=25 Kev Jackson (Guest)
on 2006-03-29 10:47
(Received via mailing list)
>>ie is it better to use args[1].to_s or "#{args[1]}"
>>
>>
>
>to_s, but if you control your $test_data and args, and can't imagine how
>args[1] or args[2] could be anything other than strings, there's no need for
>a cast at all.
>
>
>
My original goal was to allow the qc team to write

text :id, :pg_401, :name

So the arguments in theory should be symbols not strings, hence the need
for some kind of to_s/#{} hackery

>>My current thinking is that "#{}" should be used when concatenating
>>strings together with values (or interpolating), where as .to_s should be
>>used when you want the string representation of an object.
>>
>>
>
>I don't like using interpolation when the stuff I'm interpolating is bigger
>than the literal part of the string.
>
>
However, coming from a Java background, "s1" + "s2" is a performance
(memory/speed) nightmare, so I shy away from S1 + S2 and try to use
#{S1}S2 where possible.  Perhaps string + string isn't so bad in Ruby,
but old habits die hard...

Thanks
Kev
0b561a629b87f0bbf71b45ee5a48febb?d=identicon&s=25 Dave Burt (Guest)
on 2006-03-29 11:19
(Received via mailing list)
Kev Jackson wrote:
> My original goal was to allow the qc team to write
>
> text :id, :pg_401, :name
>
> So the arguments in theory should be symbols not strings, hence the need
> for some kind of to_s/#{} hackery

That's fair enough, though I'd prefer to either use strings or change
the
$test_data hash to avoid having to convert. For instance, you could use
a
HashWithIndifferentAccess from Rails' Active Support module (require
'active_support'), or you could just convert the keys to symbols as you
load
the data.

> ...
> However, coming from a Java background, "s1" + "s2" is a performance
> (memory/speed) nightmare, so I shy away from S1 + S2 and try to use
> #{S1}S2 where possible.  Perhaps string + string isn't so bad in Ruby, but
> old habits die hard...

It's not so terrible in Java either; when you want to avoid it is where
you're adding multiple times to get a single result string, especially
in a
big loop. Then you'd use a StringBuffer to avoid creating and
garbage-collecting zillions of strings. Of course, Ruby's strings are
mutable, so you don't need another class of object.

Compare:
s = ""; 50.times {|i| s += i.to_s + " "} # watch out: 50 strings are
discarded

with:
s = ""; 50.times {|i| s << i.to_s << " " } # like Java's StringBuffer:
one
object, efficient

Anyway, in this case, "#{x}y" is about the same as x + "y", because
you're
only creating one extra string. You've just got the added method-call
overhead for String#+.

> Thanks

You're welcome.

Cheers,
Dave
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2006-03-29 14:18
(Received via mailing list)
And the winner is....

-----------------------------------8<--------------------------------------

626/126 > cat stringperf.rb ; ruby stringperf.rb
#!/usr/bin/env ruby
require 'benchmark'

 n = 10000
Benchmark.bm do
        |bm|
        bm.report "String#+     " do
                n.times do
                    actual = ''
                    %w{alpha beta gamma soup}.each do
                        |x|
                        actual = actual + x
                    end
                end
        end # do

        bm.report "Interpolation" do
                n.times do
                    %w{alpha beta gamma soup}.each do
                        |x|
                        actual = "#{actual}#{x}"
                    end
                end
        end # do

        bm.report "Format       " do
                n.times do
                    %w{alpha beta gamma soup}.each do
                        |x|
                        actual = "%s%s" % [actual, x]
                    end
                end
        end
 end # do


      user     system      total        real
String#+       0.090000   0.000000   0.090000 (  0.109451)
Interpolation  0.150000   0.000000   0.150000 (  0.153926)
Format         0.210000   0.000000   0.210000 (  0.226805)
-----------------------------------8<--------------------------------------
Robert

--
Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein
0b561a629b87f0bbf71b45ee5a48febb?d=identicon&s=25 Dave Burt (Guest)
on 2006-03-29 14:18
(Received via mailing list)
Robert Dober wrote:
> And the winner is....
> ...
> String#+       0.090000   0.000000   0.090000 (  0.109451)
> Interpolation  0.150000   0.000000   0.150000 (  0.153926)
> Format         0.210000   0.000000   0.210000 (  0.226805)

String#+       +1 String
Interpolate    +1 String
Format         +1 String, +1 Array
String#<<      no new objects

Try this one:

actual << x

Cheers,
Dave
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2006-03-29 14:36
(Received via mailing list)
On 3/29/06, Dave Burt <dave@burt.id.au> wrote:


There was a different error I forgot to initialize "actual"


Dave

Excellent idea "<<".
I do not see where there are less objects in << than in +=
actually.
However << is *the* operator to use. I came up with a benchmark
constructing
much longer strings
your << (or concat) is the *best* solution.
Another approach is not to construct strings immedeatly but to build an
array and to join the array eventually. For long strings the result is
quite
speactacular (almost as fast as << )
Pleas kindly look at this
-------------------------------9<------------------------------------------
647/147 > cat string2.rb;ruby string2.rb
#!/usr/bin/env ruby
 require 'benchmark'

List = %w{ omega delta Ringo } * 50
 n = 5000
 Benchmark.bm do
        |bm|
        bm.report "explicit +" do
                n.times do
                    actual = ''
                    List.each do
                        |x|
                        actual = actual + x
                    end
                end
        end # do

        bm.report "implicit +" do
                n.times do
                    actual = ''
                    List.each do
                        |x|
                        actual += x
                    end
                end
        end # do

        bm.report "append    " do
                n.times do
                    actual = ''
                    List.each do
                        |x|
                        actual << x
                    end
                end
        end
        bm.report "Array     " do
                n.times do
                    actual = []
                    List.each do
                        |x|
                        actual << x
                    end
                    actual = actual.join("")
                end
        end
end
      user     system      total        real
explicit +  2.170000   0.010000   2.180000 (  2.336149)
implicit +  2.170000   0.010000   2.180000 (  2.635293)
append      0.730000   0.000000   0.730000 (  0.800968)
Array       0.770000   0.000000   0.770000 (  0.862098)

--------------------------------------10<-------------------------------

Cheers
Robert


--
Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-03-29 16:02
(Received via mailing list)
On Mar 28, 2006, at 10:36 PM, Kev Jackson wrote:

> My current thinking is that "#{}" should be used when concatenating
> strings together with values (or interpolating), where as .to_s
> should be used when you want the string representation of an object.

That sounds right to me.

James Edward Gray II
This topic is locked and can not be replied to.