Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9317243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 19, 20262026-06-19T02:49:34+00:00 2026-06-19T02:49:34+00:00

Ruby use the functions from functional concept heavily, such as map, each . They

  • 0

Ruby use the functions from “functional concept” heavily, such as map, each. They really depend on a self-contained function which is so called block in Ruby.

It is very common to loop though a 2d array, make an string about the elements.

In java, it may looks like

   public String toString(){
        String output = "[";
        for (int i =0; i<array.length; i++) {
            output+= "Row "+(i+1)+" : ";
            for (int j=0; j<array[0].length;j++ ) {
                output += array[i][j]+", ";
            }
            output += "\n";
        }

        return output += "]";
    }

I tried to rewrite such a thing in “Ruby functional Style”, but I think there are still some improvements. Eg. I want to remove the mutable variable output

  def to_s
        output = "[\n"
        @data.each_with_index do |row,i|
            output << "Row #{i+1} : "
            row.each { |num| output << "#{num}," }
            output << "\n"
        end

        output+"]"
    end
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-19T02:49:35+00:00Added an answer on June 19, 2026 at 2:49 am

    Whenever you see the pattern:

    1. initialize an accumulator (in your case output)
    2. on each iteration of some collection modify the accumulator (in your case append to it)
    3. return the accumulator

    that’s a fold, or in Ruby terms an inject.

    Actually, that’s a bit of a tautology. A fold is a universal method of iteration: everything that can be expressed by iterating over the elements of a collection can also be expressed as a fold over the collection. In other words: all methods on Enumerable (including each!) could also be defined in terms of inject as the primitive method instead of each.

    Think about it this way: a collection can either be empty or there can be a current element. There’s no third option, if you cover those two cases, then you have covered everything. Well, fold takes two arguments: one which tells it what to do when the collection is empty, and one which tells it what to do with the current element. Or, put yet another way: you can see a collection as a series of instructions and fold is an interpreter for those instructions. There are only two kinds of instructions: the END instruction and a VALUE(el) instruction. And you can supply the interpreter code for both those instructions to the fold.

    In Ruby, the second argument is not part of the argument list, it is the block.

    So, what’s it look like as a fold?

    def to_s
      @data.each_with_index.inject("[\n") do |acc, (row, i)|
        acc + "Row #{i+1} : #{row.join(',')}\n"
      end + ']'
    end
    

    If you’re curious about whether or not the each_with_index may infect your code with some non-functional impurity, rest assured that you can just as easily get rid of it by including the index in the accumulator:

    def to_s
      @data.inject(["[\n", 1]) do |(s, i), row|
        [s + "Row #{i} : #{row.join(',')}\n", i+1]
      end.first + ']'
    end
    

    Also note that in the first case, with the each_with_index, we’re not actually doing anything “interesting” with the accumulator, unlike the second case, where we are using it to keep count of the index. In fact, the first case is actually a restricted form of fold, it doesn’t use all of its power. It really is just a map:

    def to_s
      "[\n" + @data.map.with_index(1) do |row, i|
        "Row #{i} : #{row.join(',')}\n"
      end.join + ']'
    end
    

    In my personal opinion, it would actually be perfectly okay to use (mutable) string appending here instead of string concatenation:

    def to_s
      "[\n" << @data.map.with_index(1) do |row, i|
        "Row #{i} : #{row.join(',')}\n"
      end.join << ']'
    end
    

    This saves us from creating a couple of unnecessary string objects, but more importantly: it is more idiomatic. The real problem is shared mutable state, but we’re not sharing our mutable string here: when to_s returns its caller does get access to the string, but to_s itself has returned and thus no longer has access to it.

    If you want to get real fancy, you could even use string interpolation:

    def to_s
      %Q<[\n#{@data.map.with_index(1) do |row, i|
        "Row #{i} : #{row.join(',')}\n"
      end.join}]>
    end
    

    Unfortunately, this not only breaks IRb’s syntax highlighting, but also my brain’s 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to use these functions from the conio.c library (Borland) in Ruby, specially
I am really new to Ruby and could use some help with a program.
From my previous question about timezones , I decided to use the Ruby gem
Is there a way for me to call ruby on rails functions from within
Suppose I want to call one or more boost library functions from Ruby code.
I am new to Ruby. I'm looking to import functions from a module that
This is related to a question I asked here: Thread Locking in Ruby (use
I use Ruby on Rails 2.3 and gem 'tiny_mce' Gem uses TinyMCE 3.4 Gem
I would like to use Ruby Net::SMTP to send email. The routine send_message( msgstr,
I have to type rvm use ruby-1.9.3 every time I login to my server.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.