learning the "Ruby way"

Ask a Question related to Ruby, Design and Development.

  1. #1

    Default learning the "Ruby way"

    **Hobby-programmer alarm**

    Hello!
    I am trying to learn Ruby, but with the goal of understanding new
    elegant solutions, not to repeat the same messy solutions I usually
    come up with.
    Here is an example I would like to use to improve my understanding.
    Any pointers would be great.

    Problem:
    I have a sorted list ('alfred', 'boris', 'bruce', 'claire', 'dean', 'donald')
    and would like to generate or return ('-a-', 'alfred', '-b-', 'boris',
    'bruce', '-c-', 'claire', '-d-', 'dean', 'donald').

    Here's my solution:
    lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']
    prev = ''
    newlst = Array.new
    lst.each { |cur|
    if cur[0..0] != prev
    newlst.push("-#{cur[0..0]}-")
    end
    newlst.push(cur)
    prev = cur[0..0] }

    Is this the "Ruby way" of solving this problem? I doubt it, defining
    "helper variables" like this is what had to be done in Basic, and my
    solution doesn't demonstrate the high degree of readability Ruby is often
    praised for.

    Any useful suggestions for me? I'd be very grateful!
    Mark
    Mark Wirdnam Guest

  2. Similar Questions and Discussions

    1. learning the "Ruby way"<Pine.LNX.4.44.0311201340160.4622-100000@ool-4355dfae.dyn.optonline.net>
      Hi -- On Fri, 21 Nov 2003, Chad Fowler wrote: How strict is strict? :-) David --
    2. learning the "Ruby way"<Pine.LNX.4.44.0311201150530.4491-100000@ool-4355dfae.dyn.optonline.net><Pine.LNX.4.44.0311201137580.4435-100000@ool-4355dfae.dyn.optonline.net>
      Hi -- On Fri, 21 Nov 2003 dblack@wobblini.net wrote: Just to clarify: "This" means my solution, not your question :-) David
    3. learning the "Ruby way"<Pine.LNX.4.44.0311201137580.4435-100000@ool-4355dfae.dyn.optonline.net>
      Hi -- On Thu, 20 Nov 2003, Mark Wirdnam wrote: This may be a bit ill-advised, because it changes the array as it iterates through it (though...
    4. learning interactions - a "fill the blank" question
      Hello, I'm working on a quiz based on the learning interactions pre-build components. Since I needed to implement a "multiple text field "...
    5. ruby-mode breaks in ruby-calculate-indent after "#{}"
      I was trying to write the following code with ruby-mode on: MyClass.foo("Quoted text #{bar}", more, arguments, here) When I went to hit TAB on...
  3. #2

    Default Re: learning the "Ruby way"

    how's this?

    y = nil
    newlst = lst.collect { |x|
    y == x[0..0] ? x : y=x[0..0]; [ "-#{x[0..0]}-", x ] }
    }.flatten

    in future ruby2 y=nil may not be needed.

    -t0
    > **Hobby-programmer alarm**
    >
    > Hello!
    > I am trying to learn Ruby, but with the goal of understanding new
    > elegant solutions, not to repeat the same messy solutions I usually
    > come up with.
    > Here is an example I would like to use to improve my understanding.
    > Any pointers would be great.
    >
    > Problem:
    > I have a sorted list ('alfred', 'boris', 'bruce', 'claire', 'dean', 'donald')
    > and would like to generate or return ('-a-', 'alfred', '-b-', 'boris',
    > 'bruce', '-c-', 'claire', '-d-', 'dean', 'donald').
    >
    > Here's my solution:
    > lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']
    > prev = ''
    > newlst = Array.new
    > lst.each { |cur|
    > if cur[0..0] != prev
    > newlst.push("-#{cur[0..0]}-")
    > end
    > newlst.push(cur)
    > prev = cur[0..0] }
    >
    > Is this the "Ruby way" of solving this problem? I doubt it, defining
    > "helper variables" like this is what had to be done in Basic, and my
    > solution doesn't demonstrate the high degree of readability Ruby is often
    > praised for.
    >
    > Any useful suggestions for me? I'd be very grateful!
    > Mark
    >
    >
    T. Onoma Guest

  4. #3

    Default Re: learning the "Ruby way"

    I'm sure there are many ways of doing this, but here's one:

    lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']

    frob = lst.map do |val|
    ["-#{val[0..0]}-", val]
    end.flatten.uniq

    p frob

    I'm not sure if #uniq is defined to leave the first occurrence and
    delete all the rest or not,
    but that's what it currently does, so it works.

    - Dan


    Dan Doel Guest

  5. #4

    Default Re: learning the "Ruby way"


    "Dan Doel" <djd15@po.cwru.edu> schrieb im Newsbeitrag
    news:3FBC87DA.1090803@po.cwru.edu...
    > I'm sure there are many ways of doing this, but here's one:
    >
    > lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']
    >
    > frob = lst.map do |val|
    > ["-#{val[0..0]}-", val]
    > end.flatten.uniq
    >
    > p frob
    >
    > I'm not sure if #uniq is defined to leave the first occurrence and
    > delete all the rest or not,
    > but that's what it currently does, so it works.
    There must be an inject way of doing this...

    lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']

    frob = lst.inject( [[], nil] ) do |(res, key), word|
    k = "-#{word[0].chr}-"
    res << k unless k == key
    res << word
    [res, k]
    end[0]


    But this really cries for a Hash, because we have a typical key value
    relationship here:

    lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']

    lst.inject( Hash.new {|h,k| h[k]=[]} ) {|res,w| res["-#{w[0].chr}-"] << w;
    res}.sort.flatten

    In fact, I'd just return the Hash. Then you have the appropriate data
    structur. Simply omit ".sort.flatten" from the line above.

    Regards

    robert



    Robert Klemme Guest

  6. #5

    Default Re: learning the "Ruby way"

    On Thursday, November 20, 2003, 8:07:14 PM, Mark wrote:
    > [...]
    > Problem:
    > I have a sorted list ('alfred', 'boris', 'bruce', 'claire', 'dean', 'donald')
    > and would like to generate or return ('-a-', 'alfred', '-b-', 'boris',
    > 'bruce', '-c-', 'claire', '-d-', 'dean', 'donald').
    > Here's my solution:
    > [...]
    > Is this the "Ruby way" of solving this problem? I doubt it, defining
    > "helper variables" like this is what had to be done in Basic, and my
    > solution doesn't demonstrate the high degree of readability Ruby is often
    > praised for.
    > Any useful suggestions for me? I'd be very grateful!
    > Mark

    My first thought was to collect the values into a hash

    { 'a' => ['alfred'],
    'd' => ['dean', 'donald'],
    ... }

    then render that hash into the array that you want.

    It's unlikely to be all that efficient, but both steps are very easy.

    Cheers,
    Gavin



    Gavin Sinclair Guest

  7. #6

    Default Re: learning the "Ruby way"

    Mark Wirdnam <mark.wirdnam@stud.unibas.ch> wrote:
    >
    > Problem:
    > I have a sorted list ('alfred', 'boris', 'bruce', 'claire', 'dean', 'donald')
    > and would like to generate or return ('-a-', 'alfred', '-b-', 'boris',
    > 'bruce', '-c-', 'claire', '-d-', 'dean', 'donald').
    One more way to do it...

    require 'enum/cluster' # [url]http://redshift.sourceforge.net/enum[/url]

    lst = ['alfred', 'boris', 'bruce', 'claire', 'dean', 'donald']

    a = ["--#{lst[0][0..0]}--"]
    lst.each_cluster(2) {|i, j|
    a << i
    a << "--#{j[0..0]}--" if i[0] != j[0]
    }

    p a

    martin
    Martin DeMello Guest

  8. #7

    Default Re: learning the "Ruby way"

    On Thu, 20 Nov 2003 01:06:25 -0800, Mark Wirdnam wrote:
    > Is this the "Ruby way" of solving this problem? I doubt it, defining
    > "helper variables" like this is what had to be done in Basic, and my
    > solution doesn't demonstrate the high degree of readability Ruby is often
    > praised for.
    >
    > Any useful suggestions for me? I'd be very grateful!
    > Mark
    How about this dirty solution ?


    server> ruby a.rb
    ["-a-", "alfred", "-b-", "boris", "bruce", "-c-", "claire", "-d-", "dean", "donald"]
    server> expand a.rb
    names = %w(alfred boris bruce claire dean donald)
    letters = names.map{|name| n=name[0..0]; [n, "-#{n}-"]}.uniq
    p (letters + names.zip(names)).sort.transpose[1]
    server>


    --
    Simon Strandgaard
    Simon Strandgaard Guest

  9. #8

    Default Re: learning the "Ruby way"

    On Thu, 20 Nov 2003, Mark Wirdnam wrote:

    # **Hobby-programmer alarm**
    #

    May excellent suggestions have been made, so I won't bore you with my
    attempt. But, I wanted to say, "Welcome Hobby Programmer!"

    I'm paid to do IT work, but I have increasingly moved my programming
    activities into the land of hobby-dom, where I tend to enjoy them more. I
    find Ruby to be an *excellent* language for hobbyists (as well as
    enterprise users).

    Are there other strict hobbyists on the list?

    Chad


    Chad Fowler Guest

  10. #9

    Default Re: learning the "Ruby way"

    I am a programming hobbyist I suppose.

    I'm the Manager of the IS Group at work and I generally stick to networking,
    server maintenance/configuration(s), etc...but I have moved into using
    Ruby( as well as other languages, but Ruby is the most recent addition ) to
    make my duties at the office easier.

    Being a competent hobbyist( or i'd like to think i am ) I often spend a few
    hours up to a few days making my own mini-apps and scripts to perform
    certain duties instead of purchasing software or having me do them manually.

    Don't worry all you real programmers out there we have real programmers at
    the office to. =)

    Zach



    -----Original Message-----
    From: Chad Fowler [mailto:chad@chadfowler.com]
    Sent: Thursday, November 20, 2003 1:29 PM
    To: ruby-talk ML
    Subject: Re: learning the "Ruby way"


    On Thu, 20 Nov 2003, Mark Wirdnam wrote:

    # **Hobby-programmer alarm**
    #

    May excellent suggestions have been made, so I won't bore you with my
    attempt. But, I wanted to say, "Welcome Hobby Programmer!"

    I'm paid to do IT work, but I have increasingly moved my programming
    activities into the land of hobby-dom, where I tend to enjoy them more. I
    find Ruby to be an *excellent* language for hobbyists (as well as
    enterprise users).

    Are there other strict hobbyists on the list?

    Chad




    Zach Dennis Guest

  11. #10

    Default Re: learning the "Ruby way"

    On Thu, 2003-11-20 at 13:28, Chad Fowler wrote:
    > On Thu, 20 Nov 2003, Mark Wirdnam wrote:
    >
    > # **Hobby-programmer alarm**
    > #
    >
    > May excellent suggestions have been made, so I won't bore you with my
    > attempt. But, I wanted to say, "Welcome Hobby Programmer!"
    >
    > I'm paid to do IT work, but I have increasingly moved my programming
    > activities into the land of hobby-dom, where I tend to enjoy them more. I
    > find Ruby to be an *excellent* language for hobbyists (as well as
    > enterprise users).
    >
    > Are there other strict hobbyists on the list?
    I'm an administrator rather than a programmer by trade, although as with
    any admin job that also entails a fair amount of scripting, and my own
    position also includes some C debugging and packaging.

    On the other hand I learned Ruby scritly for hobby use, since at work
    we're stuck pretty firmly with Perl and POSIX shell. Now I'm spending
    what hours I can spare working on Ruby-GNOME2 (mostly docs and bugfixes)
    and a little media player which may actually be worth regular end users
    looking at some day. ;)

    --
    Matthew Berg <galt@gothpoodle.com>



    Matthew Berg Guest

  12. #11

    Default Re: learning the "Ruby way"

    On Friday, November 21, 2003, 5:34:06 AM, dblack wrote:
    > Hi --
    > On Fri, 21 Nov 2003, Chad Fowler wrote:
    >> On Thu, 20 Nov 2003, Mark Wirdnam wrote:
    >>
    >> # **Hobby-programmer alarm**
    >> #
    >>
    >> May excellent suggestions have been made, so I won't bore you with my
    >> attempt. But, I wanted to say, "Welcome Hobby Programmer!"
    >>
    >> I'm paid to do IT work, but I have increasingly moved my programming
    >> activities into the land of hobby-dom, where I tend to enjoy them more. I
    >> find Ruby to be an *excellent* language for hobbyists (as well as
    >> enterprise users).
    >>
    >> Are there other strict hobbyists on the list?
    > How strict is strict? :-)
    I get by by just implementing a few methods from Hobby::Programmer :)

    Gavin


    Gavin Sinclair Guest

  13. #12

    Default Re: learning the "Ruby way"

    Chad Fowler <chad@chadfowler.com> wrote:
    > Are there other strict hobbyists on the list?
    "Hobbyist"? What happened to "hacker"?

    Hopefully I'll graduate in March with a Bachelor of Software
    Engineering, however until then you can call me a hobbyist if you must
    but I prefer the term hacker because I'm one of those snooty people who
    insists on "real" definitions even when the mainstream ones get changed.
    :-)

    In Ruby I've only written small programs which transform data and
    interesting little toy scripts. But I skim this list every day and I
    have a vapourware Ruby roguelike game in the works which is fun to
    design and code random small bits when I have time away from
    assignments, thesis and (hopefully soon) work.

    --
    Greg McIntyre ======[ [email]greg@puyo.cjb.net[/email] ]===[ [url]http://puyo.cjb.net[/url] ]===
    Greg McIntyre Guest

  14. #13

    Default Re: learning the "Ruby way"

    --8JPrznbw0YAQ/KXy
    Content-Type: text/plain; charset=us-ascii
    Content-Disposition: inline
    Content-Transfer-Encoding: quoted-printable
    > In Ruby I've only written small programs which transform data and
    > interesting little toy scripts. But I skim this list every day and I
    > have a vapourware Ruby roguelike game in the works which is fun to
    > design and code random small bits when I have time away from
    > assignments, thesis and (hopefully soon) work.
    A roguelike game written in Ruby would be very interesting to see.
    Especially if it was easy to add new elements to the game in ruby. If
    you ever get something releasable, be sure to let us know.

    --=20
    Zachary P. Landau <kapheine@hypa.net>
    GPG: gpg --recv-key 0x24E5AD99 | [url]http://kapheine.hypa.net/kapheine.asc[/url]

    --8JPrznbw0YAQ/KXy
    Content-Type: application/pgp-signature
    Content-Disposition: inline

    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.2.3 (GNU/Linux)

    iD8DBQE/vWKnCwWyMCTlrZkRAk3oAJ0VvJ7bd3eRGmO2ufOFRRAXgfnG3A CfRdd2
    zfBcQRk9oGi9atPuipddtkg=
    =UaIt
    -----END PGP SIGNATURE-----

    --8JPrznbw0YAQ/KXy--


    Zachary P. Landau Guest

  15. #14

    Default Re: learning the "Ruby way"

    "Zachary P. Landau" <kapheine@hypa.net> wrote:
    > > In Ruby I've only written small programs which transform data and
    > > interesting little toy scripts. But I skim this list every day and I
    > > have a vapourware Ruby roguelike game in the works which is fun to
    > > design and code random small bits when I have time away from
    > > assignments, thesis and (hopefully soon) work.
    >
    > A roguelike game written in Ruby would be very interesting to see.
    > Especially if it was easy to add new elements to the game in ruby. If
    > you ever get something releasable, be sure to let us know.
    I think Ruby's a great language for it. I chose it because I wanted
    others, possibly non-professional programmers, to be able to "write"
    for it (create levels, dialogue, etc.). Ruby's so intuitive and
    easy that I thought it would be good.

    That's why I find the long raging discussion on interfaces interesting
    -- novice programmers are going to get things wrong so it'd be nice if I
    could make their code adhere to an interface, or at least warn them when
    it doesn't. I mucked about with doing this in Ruby 1.8 and ended up with
    modules which assert certain methods exist in the classes in which they
    are included, at the point of their inclusion. It's a simple and
    not-perfect check but it is transparent check from the point of the
    "writer" but it does combat forgetfulness.

    Here's a taste...

    This is a map definition. Do I store it in XML? No. Do I store it as my
    own special file format? No. It's in Ruby! Yey! :) Doing this makes map
    definitions very flexible (e.g. it could be fully or partially randomly
    generated upon definition).

    The map definition is a class with a constant for layout and a constant
    for a "key" (in the cartography sense). Each tile on the map contains a
    bunch of stuff with no certain arrangement (I'm currently unsure if
    that's desirable... still thinking about it). Map::inherited is defined
    to collect map definitions into a list. I have a demo in which you can
    walk around this map, bump into things and set off the trap. Very
    simple, but I'm still thinking about the design of the fundamentals, so
    I didn't want to get carried away (and because I'm a hobbyist/hacker).

    Anyway, I'm posting it because it's a nice example of Ruby's power and
    flexibility being used. :)

    -------------

    class DemoMap < Map

    class SpecialTrap
    def triggered_by(actor)
    end

    include Triggerable # asserts triggered_by is defined
    end

    LAYOUT =<<END_LAYOUT
    ###########
    0...=...t.#
    #.........1
    #.........####
    #............#
    ####.........#
    #.........#
    #.........#
    ###########
    END_LAYOUT

    KEY = {
    '.' => Ground,
    '#' => BorderWall,
    '=' => [
    Ground,
    Table,
    ],
    '0' => [
    Ground,
    Marker.new(0),
    Teleport.new(DemoMap, 1),
    Door.new(open=true),
    ],
    't' => [
    Ground,
    SpecialTrap,
    ],
    '1' => [
    Ground,
    Marker.new(1),
    Teleport.new(DemoMap, 0),
    Door.new(open=false),
    ],
    }
    end

    --
    Greg McIntyre ======[ [email]greg@puyo.cjb.net[/email] ]===[ [url]http://puyo.cjb.net[/url] ]===
    Greg McIntyre Guest

  16. #15

    Default Re: learning the "Ruby way"

    On Thu, 2003-11-20 at 20:37, Greg McIntyre wrote:
    <lots of nifty stuff snipped>
    > LAYOUT =<<END_LAYOUT
    > ###########
    > 0...=...t.#
    > #.........1
    > #.........####
    > #............#
    > ####.........#
    > #.........#
    > #.........#
    > ###########
    > END_LAYOUT
    Very cool! I've been poking around the Doom WAD spec a bit, try to see
    how feasible it would be to generate new levels with something like:

    l = Level.new(10,10)
    l.add(Wall.new(0,0,5,5))
    l.set_spawn_point(5,0)

    and so forth. But this looks like a much nicer way to do it.

    Yours,

    Tom


    Tom Copeland Guest

  17. #16

    Default Re: learning the "Ruby way"

    > On Thu, 2003-11-20 at 20:37, Greg McIntyre wrote:
    > <lots of nifty stuff snipped>
    > > LAYOUT =<<END_LAYOUT
    > > ###########
    > > 0...=...t.#
    > > #.........1
    > > #.........####
    > > #............#
    > > ####.........#
    > > #.........#
    > > #.........#
    > > ###########
    > > END_LAYOUT
    Wow, Nethack is being reinvented, again.

    -- Dossy

    --
    Dossy Shiobara mail: [email]dossy@panoptic.com[/email]
    Panoptic Computer Network web: [url]http://www.panoptic.com/[/url]
    "He realized the fastest way to change is to laugh at your own
    folly -- then you can let go and quickly move on." (p. 70)


    Dossy Guest

  18. #17

    Default Re: learning the "Ruby way"

    Dossy <dossy@panoptic.com> wrote:
    > Wow, Nethack is being reinvented, again.
    Heaven forbid! I hate that game. :-)

    --
    Greg McIntyre ======[ [email]greg@puyo.cjb.net[/email] ]===[ [url]http://puyo.cjb.net[/url] ]===
    Greg McIntyre Guest

  19. #18

    Default Re: learning the "Ruby way"

    Dossy <dossy@panoptic.com> wrote:
    >> On Thu, 2003-11-20 at 20:37, Greg McIntyre wrote:
    >> <lots of nifty stuff snipped>
    >> > LAYOUT =<<END_LAYOUT
    >> > ###########
    >> > 0...=...t.#
    >> > #.........1
    >> > #.........####
    >> > #............#
    >> > ####.........#
    >> > #.........#
    >> > #.........#
    >> > ###########
    >> > END_LAYOUT
    >
    > Wow, Nethack is being reinvented, again.
    He did say it was a roguelike.

    martin
    Martin DeMello Guest

  20. #19

    Default Re: learning the "Ruby way"

    ok, I'm not quite there yet, but your helpful examples have given me
    an idea how to go about things in Ruby. I think I see a main theme
    being to use the power of the pre-defined methods of the
    array/string/whatever.
    Thanks for your help!

    Mark
    Mark Wirdnam Guest

Posting Permissions

  • You may not post new threads
  • You may post replies
  • You may not post attachments
  • You may not edit your posts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139