adding anotehr each method to String

Discussion in 'Ruby' started by Chris Shea, Mar 25, 2007.

  1. Chris Shea

    Chris Shea Guest

    On Mar 25, 2:20 am, (Une
    Bévue) wrote:
    > f it doesn't exist allready, i'd like to add another each method to
    > String similar to each_byte except it loops over chars for example :
    >
    > "zero".each_char{|c| puts c}
    >
    > would print-out :
    > z
    > e
    > r
    > o
    >
    > i know how to add a new method to a given class, what i don't know is
    > specifically for methods like each which pass an arg to a given block...
    >
    > --
    > It's easy to play any musical instrument: all you have to do is
    > touch the right key at the right time and the instrument will
    > play itself. -- J.S. Bach


    What you need is "yield".

    This does what you need:

    class String
    def each_char
    0.upto(self.length - 1) do |x|
    yield self[x,1]
    end
    end
    end

    yield passes a value to a block.
    Chris Shea, Mar 25, 2007
    #1
    1. Advertising

  2. Chris Shea

    John Joyce Guest

    Might not do what you expect.
    under current conditions you might get:
    =A8
    u

    instead of
    =FC


    On Mar 25, 2007, at 4:25 PM, Une B=E9vue wrote:

    > f it doesn't exist allready, i'd like to add another each method to
    > String similar to each_byte except it loops over chars for example :
    >
    > "zero".each_char{|c| puts c}
    >
    > would print-out :
    > z
    > e
    > r
    > o
    >
    > i know how to add a new method to a given class, what i don't know is
    > specifically for methods like each which pass an arg to a given =20
    > block...
    >
    >
    > --=20
    > It's easy to play any musical instrument: all you have to do is
    > touch the right key at the right time and the instrument will
    > play itself. -- J.S. Bach
    >
    John Joyce, Mar 25, 2007
    #2
    1. Advertising

  3. Chris Shea

    Une Bévue Guest

    f it doesn't exist allready, i'd like to add another each method to
    String similar to each_byte except it loops over chars for example :

    "zero".each_char{|c| puts c}

    would print-out :
    z
    e
    r
    o

    i know how to add a new method to a given class, what i don't know is
    specifically for methods like each which pass an arg to a given block...


    --
    It's easy to play any musical instrument: all you have to do is
    touch the right key at the right time and the instrument will
    play itself. -- J.S. Bach
    Une Bévue, Mar 25, 2007
    #3
  4. Chris Shea

    John Joyce Guest

    I mean you should check into the way Ruby works with multi-byte =20
    characters!
    But this should be watched carefully with every language.
    Typing multibyte characters on many windows systems is a pain in the =20
    behind. Luckily it's not so painful on osx, so I can type an umlaut =20
    by option+u then the character I want it over.
    Here is what happens...

    irb(main):001:0> mystring =3D"\303\274mlaut"
    =3D> "\303\274mlaut"
    irb(main):002:0> puts mystring
    =FCmlaut
    =3D> nil
    irb(main):003:0> puts mystring.length
    7
    =3D> nil


    On Mar 25, 2007, at 5:25 PM, Une B=E9vue wrote:

    > John Joyce <> wrote:
    >
    >> Might not do what you expect.
    >> under current conditions you might get:
    >> =A8
    >> u
    >>
    >> instead of
    >> =FC

    >
    > then, u mean, it wouldn't work with NON-ASCII chars ?
    >
    > it doesn't matter in fact because i'm playing with US-ASCII chars only
    > in that case.
    >
    > but thanks a lot, better to know !
    > --=20
    > It's easy to play any musical instrument: all you have to do is
    > touch the right key at the right time and the instrument will
    > play itself. -- J.S. Bach
    >
    John Joyce, Mar 25, 2007
    #4
  5. Chris Shea

    Une Bévue Guest

    John Joyce <> wrote:

    > Might not do what you expect.
    > under current conditions you might get:
    > ¨
    > u
    >
    > instead of
    > ü


    then, u mean, it wouldn't work with NON-ASCII chars ?

    it doesn't matter in fact because i'm playing with US-ASCII chars only
    in that case.

    but thanks a lot, better to know !
    --
    It's easy to play any musical instrument: all you have to do is
    touch the right key at the right time and the instrument will
    play itself. -- J.S. Bach
    Une Bévue, Mar 25, 2007
    #5
  6. Chris Shea

    Une Bévue Guest

    Chris Shea <> wrote:

    >
    > What you need is "yield".
    >
    > This does what you need:
    >
    > class String
    > def each_char
    > 0.upto(self.length - 1) do |x|
    > yield self[x,1]
    > end
    > end
    > end
    >
    > yield passes a value to a block.


    Ok, fine thanks a lot !

    does the method :
    String.to_a doing :

    s="a string"
    sa=s.to_a
    #=> ['a',' ','s','t','r','i','n','g']

    exists allready ?

    generally speaking how to list-out, for a given class all the methods ?

    in order to avoid collapsing them.
    --
    It's easy to play any musical instrument: all you have to do is
    touch the right key at the right time and the instrument will
    play itself. -- J.S. Bach
    Une Bévue, Mar 25, 2007
    #6
  7. On 3/25/07, Une B=E9vue <> wrote:
    > Ok, fine thanks a lot !
    >
    > does the method :
    > String.to_a doing :
    >
    > s=3D"a string"
    > sa=3Ds.to_a
    > #=3D> ['a',' ','s','t','r','i','n','g']
    >
    > exists allready ?
    >


    irb(main):001:0> "a string".split( "" )
    =3D> ["a", " ", "s", "t", "r", "i", "n", "g"]

    > generally speaking how to list-out, for a given class all the methods ?
    >


    irb(main):002:0> "a string".methods.sort
    =3D> ["%", "*", "+", "<", "<<", "<=3D", "<=3D>", "=3D=3D", "=3D=3D=3D", "=
    =3D~", ">", ">=3D", "[]", "
    []=3D", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "ca=
    pitaliz
    e!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clo=
    ne",
    "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "disp=
    lay",
    "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", =
    "each
    _with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "fin=
    d_all
    ", "freeze", "frozen?", "gem", "grep", "gsub", "gsub!", "hash", "hex", "id"=
    , "in
    clude?", "index", "inject", "insert", "inspect", "instance_eval", "instance=
    _of?"
    , "instance_variable_defined?", "instance_variable_get", "instance_variable=
    _set"
    , "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_y=
    aml?"
    , "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max"=
    , "me
    mber?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "=
    oct",
    "partition", "private_methods", "protected_methods", "public_methods", "re=
    ject"
    , "replace", "require", "require_gem", "respond_to?", "reverse", "reverse!"=
    , "ri
    ndex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_m=
    ethod
    s", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "sque=
    eze!"
    , "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "sw=
    apcas
    e!", "taguri", "taguri=3D", "taint", "tainted?", "to_a", "to_f", "to_i", "t=
    o_s", "
    to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", =
    "tr!"
    , "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto"=
    , "zi
    p"]

    ;)

    Hope that helps,
    -Harold
    Harold Hausman, Mar 25, 2007
    #7
  8. Chris Shea

    Une Bévue Guest

    John Joyce <> wrote:

    > I mean you should check into the way Ruby works with multi-byte
    > characters!


    because i'm a french guy, i knew that )))

    but, as writen, for such a tiny script I'll restrict to US-ASCII
    converting :

    grüß

    to

    gruess

    if y would be a german guy )))

    in french it's easier i'll convert all the :

    éèêë to e und so weiter !

    i'll have to check (as for the german ß) for ligatures too :

    æ -> ae again und so weiter !

    thanks !
    > But this should be watched carefully with every language.
    > Typing multibyte characters on many windows systems is a pain in the
    > behind. Luckily it's not so painful on osx, so I can type an umlaut
    > by option+u then the character I want it over.
    > Here is what happens...
    >
    > irb(main):001:0> mystring ="\303\274mlaut"
    > => "\303\274mlaut"
    > irb(main):002:0> puts mystring
    > ümlaut
    > => nil
    > irb(main):003:0> puts mystring.length
    > 7
    > => nil



    --
    It's easy to play any musical instrument: all you have to do is
    touch the right key at the right time and the instrument will
    play itself. -- J.S. Bach
    Une Bévue, Mar 25, 2007
    #8
  9. Chris Shea

    Une Bévue Guest

    Une Bévue <> wrote:

    >
    > exists allready ?


    Yes, following :

    ms=String.methods
    puts ms.include?('to_a')


    however :
    s='toto'
    s.to_a
    # => ['toto']


    --
    It's easy to play any musical instrument: all you have to do is
    touch the right key at the right time and the instrument will
    play itself. -- J.S. Bach
    Une Bévue, Mar 25, 2007
    #9
  10. Chris Shea

    Une Bévue Guest

    Harold Hausman <> wrote:

    >
    > irb(main):001:0> "a string".split( "" )
    > => ["a", " ", "s", "t", "r", "i", "n", "g"]


    OK fine, then no need to extend String )))
    >
    > > generally speaking how to list-out, for a given class all the methods ?
    > >

    >
    > irb(main):002:0> "a string".methods.sort => ["%", "*", "+", "<", "<<",
    > "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", " []=", "__id__",
    > "__send__", "all?", "any?", "between?", "capitalize", "capitaliz e!",
    > "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone",
    > "collect", "concat", "count", "crypt", "delete", "delete!", "detect",
    > "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte",
    > "each_line", "each _with_index", "empty?", "entries", "eql?", "equal?",
    > "extend", "find", "find_all ", "freeze", "frozen?", "gem", "grep", "gsub",
    > "gsub!", "hash", "hex", "id", "in clude?", "index", "inject", "insert",
    > "inspect", "instance_eval", "instance_of?" , "instance_variable_defined?",
    > "instance_variable_get", "instance_variable_set" , "instance_variables",
    > "intern", "is_a?", "is_binary_data?", "is_complex_yaml?" , "kind_of?",
    > "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "me mber?",
    > "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct",
    > "partition", "private_methods", "protected_methods", "public_methods",
    > "reject" , "replace", "require", "require_gem", "respond_to?", "reverse",
    > "reverse!", "ri ndex", "rjust", "rstrip", "rstrip!", "scan", "select",
    > "send", "singleton_method s", "size", "slice", "slice!", "sort",
    > "sort_by", "split", "squeeze", "squeeze!" , "strip", "strip!", "sub",
    > "sub!", "succ", "succ!", "sum", "swapcase", "swapcas e!", "taguri",
    > "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", " to_str",
    > "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!" ,
    > "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto",
    > "zi
    > p"]
    >
    > ;)
    >
    > Hope that helps,


    Yes a lot, thanks again !
    --
    It's easy to play any musical instrument: all you have to do is
    touch the right key at the right time and the instrument will
    play itself. -- J.S. Bach
    Une Bévue, Mar 25, 2007
    #10
  11. Chris Shea

    Trans Guest

    On Mar 25, 6:00 am, (Une
    B=E9vue) wrote:
    > Harold Hausman <> wrote:
    >
    > > irb(main):001:0> "a string".split( "" )
    > > =3D> ["a", " ", "s", "t", "r", "i", "n", "g"]


    "a string".split(//)

    T=2E
    Trans, Mar 25, 2007
    #11
  12. Hi,

    Am Sonntag, 25. M=E4r 2007, 16:25:05 +0900 schrieb Une B=E9vue:
    > "zero".each_char{|c| puts c}
    >=20
    > would print-out :
    > z
    > e
    > r
    > o


    The split method was already proposed.

    "another".split //
    "another".split ""
    "another".scan /./
    "=E4n=F6th=E9r".scan /./u # will preserve UTF-8 characters

    "another".each_byte { |x| c =3D x.chr ; ... }
    "another".unpack( "C*")
    "=E4n=F6th=E9r".unpack( "U*")

    Bertram


    --=20
    Bertram Scharpf
    Stuttgart, Deutschland/Germany
    http://www.bertram-scharpf.de
    Bertram Scharpf, Mar 25, 2007
    #12
  13. On Mar 25, 2007, at 2:25 AM, Une B=E9vue wrote:

    > f it doesn't exist allready, i'd like to add another each method to
    > String similar to each_byte except it loops over chars for example :
    >
    > "zero".each_char{|c| puts c}
    >
    > would print-out :
    > z
    > e
    > r
    > o


    #!/usr/bin/env ruby -wKU

    require "jcode"

    "zero".each_char { |chr| p chr }
    # >> "z"
    # >> "e"
    # >> "r"
    # >> "o"

    __END__

    James Edward Gray II=
    James Edward Gray II, Mar 26, 2007
    #13
  14. Chris Shea

    Une Bévue Guest

    James Edward Gray II <> wrote:

    >
    > #!/usr/bin/env ruby -wKU
    >
    > require "jcode"
    >
    > "zero".each_char { |chr| p chr }
    > # >> "z"
    > # >> "e"
    > # >> "r"
    > # >> "o"
    >
    > __END__


    thanks to all !


    --
    Une Bévue
    Une Bévue, Mar 26, 2007
    #14
  15. On 3/25/07, Une B=E9vue <> wrote:
    > Une B=E9vue <> wrote:
    >
    > >
    > > exists allready ?

    >
    > Yes, following :
    >
    > ms=3DString.methods
    > puts ms.include?('to_a')
    >
    >
    > however :
    > s=3D'toto'
    > s.to_a
    > # =3D> ['toto']


    This is because in Ruby a String doesn't act as a collection of
    characters, it acts as a collection of lines.

    s =3D "to\nto"
    s.to_a =3D> ["to\n", "to"]

    "to\nto".each {|l| puts l}
    to
    to

    --=20
    Rick DeNatale

    My blog on Ruby
    http://talklikeaduck.denhaven2.com/
    Rick DeNatale, Mar 26, 2007
    #15
  16. Chris Shea

    Phrogz Guest

    On Mar 26, 4:53 pm, "Rick DeNatale" <> wrote:
    > On 3/25/07, Une Bévue <> wrote:
    > > s='toto'
    > > s.to_a
    > > # => ['toto']

    >
    > This is because in Ruby a String doesn't act as a collection of
    > characters, it acts as a collection of lines.
    >
    > s = "to\nto"
    > s.to_a => ["to\n", "to"]


    To be pedantic, it's not really a collection of lines. It's a
    collection of stuff-terminated-by-some-arbitrary-character-sequence.
    The global variable $/ holds this special string:

    >> $/

    => "\n"

    >> s = "foo-bar\njim-jam"

    => "foo-bar\njim-jam"

    >> s.to_a

    => ["foo-bar\n", "jim-jam"]

    >> $/ = '-'

    => "-"
    >> s.to_a

    => ["foo-", "bar\njim-", "jam"]

    >> $/ = "bar"

    => "bar"
    >> s.to_a

    => ["foo-bar", "\njim-jam"]
    Phrogz, Mar 27, 2007
    #16
  17. On 3/26/07, Phrogz <> wrote:
    > On Mar 26, 4:53 pm, "Rick DeNatale" <> wrote:
    > > On 3/25/07, Une B=E9vue <> wro=

    te:
    > > > s=3D'toto'
    > > > s.to_a
    > > > # =3D> ['toto']

    > >
    > > This is because in Ruby a String doesn't act as a collection of
    > > characters, it acts as a collection of lines.
    > >
    > > s =3D "to\nto"
    > > s.to_a =3D> ["to\n", "to"]

    >
    > To be pedantic, it's not really a collection of lines. It's a
    > collection of stuff-terminated-by-some-arbitrary-character-sequence.
    > The global variable $/ holds this special string


    I think that a better name for
    "stuff-terminated-by-some-arbitrary-character-sequence" would be
    record. At least the 'english' library seems to think so since it
    aliases $RS and $INPUT_RECORD_SEPARATOR to $/

    --=20
    Rick DeNatale

    My blog on Ruby
    http://talklikeaduck.denhaven2.com/
    Rick DeNatale, Mar 27, 2007
    #17
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Blair
    Replies:
    1
    Views:
    409
    Eliyahu Goldin
    Aug 3, 2005
  2. Tjerk Wolterink

    xsl:for-each for each 3 elements problem

    Tjerk Wolterink, Nov 3, 2004, in forum: XML
    Replies:
    3
    Views:
    426
    Tjerk Wolterink
    Nov 3, 2004
  3. Pat Maddox
    Replies:
    6
    Views:
    152
    Marcin Mielżyński
    Jan 20, 2006
  4. Igor Nn
    Replies:
    7
    Views:
    435
    Johnny Morrice
    May 28, 2011
  5. PerlFAQ Server
    Replies:
    0
    Views:
    136
    PerlFAQ Server
    Jan 26, 2011
Loading...

Share This Page