/r/learnruby

Photograph via snooOG

This is a subreddit dedicated to the Ruby programming language. From Beginners to Professional developers, everyone is welcome to learn and share!


Beginner Ruby Tutorials

Ruby on Rails Tutorials

Other Helpful Links

Related Subreddits


Flair

We have three different levels of flair: Beginner, Intermediate, and Advanced. Feel free to mark whatever skill level you would identify yourself as realistically. We use the honor system here.


Comments and Suggestions?

Message the Mods!

Don't know where to start? Try some lessons over at Codecademy!

/r/learnruby

2,560 Subscribers

5

Getting to ALL solutions of the n-Queens Problem

Been stuck with this for a while now - I am trying to get all solutions for the n-queens problem.

I have already implemented the following code, which gets me to one solution, but I am having a hard time figuring out how I could get it to achieve all solutions:

class NQueens
    def initialize(size = 8)
        @size = size
        @board = Array.new(@size) { Array.new(@size, 0) }
    end

    def print
        @board.each { |row| puts row.join(" ") }
    end

    def place_queen(row, col)
        @board[row][col] = 1
    end

    def reset(row, col)
        @board[row][col] = 0
    end

    def clear_board
        @board.each { |row| row.map! { |position| position = 0 }}
    end

    def valid_placement?(row, col)
        # Return false if there is another queen in this row.
        if @board[row].any? { |field| field == 1 }
            return false
        # Return false if there is another queen in this col.
        elsif @board.any? { |row| row[col] == 1 }
            return false
        # Return if there is another queen in a diagonal.
        elsif !valid_diagonal_placement?(row, col)
            return false
        end
        true
    end

    def valid_diagonal_placement?(row, col)
        # For diagonals that go from top left to bottom right, the difference of
        # row - col is equal. For example (0 - 0 = 0) and (1 - 1 = 0). For 
        # diagonals that go from bottom left to top right, the sums of row + col
        # are equal. For example (7 + 0 = 7) and (6 + 1 = 7).
        dif = row - col
        sum = row + col
        
        (0..@size-1).each do |i|
            (0...@size).each do |j|
                if i + j == sum || i - j == dif
                    return false if @board[i][j] == 1
                end
            end
        end
        true
    end

    def backtrack(row = 0)
        # Print board and return true when the base case has been reached.
        if row == @size-1
            puts "\nSolution:\n\n"
            self.print
            return true
        end
        
        # If base case has not been reached, try to place a queen. We are iterating
        # through the columns of the current row (beginning from 0) until a valid
        # placement has been found or not been found, reaching the end of the row.
        (0..@size-1).each do |col|
            if valid_placement?(row, col)
                place_queen(row, col)
                
                # By calling our backtrack method with row + 1, we are checking if
                # a queen can be placed in the subsequent row.
                if backtrack(row + 1)
                    return true
                else
                    reset(row, col)
                end
            end
        end

        # Return false if we have not been able to place a queen.
        return false
    end

    def solve(@size, col = 0, )
    
end

I feel that not much is missing, but I am failing to grasp what exactly I'd need to do.

I was thinking of another recursive function or a loop around my already existing backtracking function, but I don't really understand what my base case will look like... or in other words, how will I know that I have in fact found ALL the solutions?

Thanks in advance!

3 Comments
2021/10/21
18:07 UTC

5

Data Structures and Algorithms in Ruby: Linked Lists Part #2

0 Comments
2021/09/19
23:21 UTC

6

Data Structures and Algorithms in Ruby: Linked Lists

0 Comments
2021/09/12
16:33 UTC

5

I don't understand this CodeAcadamy Solution!

Hey, I'm going through ruby. I have some rudimentary skill with javascript, nothing fancy, still gotta refer to docs for most things.

That said, I'm on the section "Iterating Over Multidimensional Arrays" where I must

Puts out every element inside the sub-arrays inside s. Iterate through .each element in the s array. Call the elements sub_array. Then iterate through .each sub_array and puts out their items.

The solution is:

s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

sub_array = 0
s.each do |x| sub_array = x
sub_array.each do |y| puts y end
end

My solution that didn't work was:

s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

s.each  { |x, y| puts "#{x}" "#{y}" }

It didn't work. I know I missed the sub_array part but do not understand how to integrate it or what's happening....

8 Comments
2021/07/26
22:37 UTC

5

Is there any reason to use map instead of each in this method?

Here's the overall code from [this article] (https://www.sitepoint.com/choosing-right-serialization-format/), where the method in question is serialize

require 'json'

#mixin
module BasicSerializable

  #should point to a class; change to a different
  #class (e.g. MessagePack, JSON, YAML) to get a different
  #serialization
  @@serializer = JSON

  def serialize
    obj = {}
    instance_variables.map do |var|
      obj[var] = instance_variable_get(var)
    end

    @@serializer.dump obj
  end

  def unserialize(string)
    obj = @@serializer.parse(string)
    obj.keys.each do |key|
      instance_variable_set(key, obj[key])
    end
  end
end

I'm new to Ruby, but I don't see what use map has over just using each in this scenario. It looks like this code is using map just to loop over each value in instance_variables, which seems silly. But I might be missing something. Am I?

2 Comments
2021/07/07
17:16 UTC

4

'write' : not opened for writing ??

I'm reading [this article on I/O in Ruby] (https://thoughtbot.com/blog/io-in-ruby) and I'm trying out my own examples, but I can't get writing to work.

This code

fd = IO.sysopen("foo.txt", "w+")
foo = IO.new(fd)
foo.puts "new text"

generates this error

./io.rb:3:in `write': not opened for writing (IOError)
        from ./io.rb:3:in `puts'
        from ./io.rb:3:in `<main>'

What am I doing wrong? I'm doing this in an actual .rb file instead of in irb, and I'm on Windows instead of a Unix system. Other than those two things, I think my code is similar to the article.

It seems like the file doesn't stay open? like I need to do something to make it stay open? Not sure if this is it, but if it is, I'm very confused as to why the article examples didn't need to do that. Was it because it was writing to /dev/null??

3 Comments
2021/07/07
01:04 UTC

3

Ruby Frameworks

Ruby is a programming language that has been accepted with open arms since 1995, and thanks to its open-source nature, it is still growing every day. Ruby is fast, object-oriented, and secure, which brings a dynamic nature into the project with an MVC support structure that makes development more comfortable than ever. With start-ups openly accepting Ruby, the language has shown remarkable progress in almost every field, especially web development.

Ruby’s popularity motivated people to take the development to the next level and bring out some best ruby frameworks for the developers. Some frameworks are built to ease out middleware and request/response of the application. Some are made for REST APIs and others for web applications. Collecting the best ruby frameworks from across the globe, in this post, we’ll talk about these frameworks and how each framework lets the developer take advantage of Ruby.

Without further ado, let’s delve into details of the best ruby frameworks for web development that will surely benefit your business.

1 Comment
2021/06/09
13:50 UTC

8

Algorithms are just abstract methods

I’m learning about data structures and algorithms and how to implement trees. And I just had an epiphany that algorithms are just an idea and that methods are the concrete form of what that idea is.

It seems like in order to be a great software engineer, I have to think about think abstractly and then make that idea concrete concrete through code through methods, classes, etc. and the way to do that is through Having an idea, creating and algorithm for it and then bringing it to life with methods(code)

Just wanted to share something that was mind opening to me.

0 Comments
2021/01/16
23:21 UTC

3

Why is recursion so hard!!!

I’m learning Ruby through App academy’s free online course. And man is it hard! I don’t know how long it will take me to get through this. But I’m on Recursion right now. Does any know what are the best ways to practice this? I find myself falling behind schedule because I can’t solve the coding problem.

Any pointers are welcomed.

9 Comments
2020/12/28
23:57 UTC

6

Newbies Together - anyone would like to embrace simple projects to help In Learning Process?

Hi There I am still on a very initial stage of learning Ruby and RoR and i miss simple projects to engage because this is the way i think more efective to Learn : CODE to Solve Real problems. Anyone with same undertanding that would like to seek and work simple projects together ?

Any comments welcome

2 Comments
2020/10/09
01:30 UTC

2

Using multiple flags with "optparse", how's that possible?

I'm working on a CLI tool and I found optparse really useful. But I found out with something like :

OptionParser.new do |opt|
    opt.on("--s S"){|o| options[:s] = o}
    opt.on("--p P"){|o| options[:p] = o}
end.parse!

It only will be understanding one argument, by the way I need my tool to be :

tool --a ARG1 --b ARG2

So, what can I do then?

1 Comment
2020/09/28
09:24 UTC

1

Find same elements in arrays using inject(:&)

arr1 = [1,2,3]
arr2 = [2,3,4]
combined = [arr1,arr2]
combined.inject(:&) ---> [2,3]

I don't understand how it works. I found that snippet on a tutorial and I have tried to google it but nothing came up

2 Comments
2020/07/24
03:14 UTC

1

Does the write variable = 0.22?

Hi all - trying to pick up Ruby going through an exercise and when I puts write (variable below it gives me 0) I thought it should be 0.22 as 22/100 = 0.22

    number = 22
    left = number
    write = left/100 
    puts write # output is 0
    left = left - write*100

Can anyone explain why it is giving 0?

3 Comments
2020/07/09
04:07 UTC

7

Books for learning to think like a programmer

Hi All,

So, one thing that I'm learning is that I am really good at picking up syntax but struggle to think like a programmer about how to solve problems and implement ideas. Has anybody found books that are good for thinking through that process?

Thanks in advance.

2 Comments
2020/07/04
16:19 UTC

1

Running a shortcut file in Ruby

Hello, friends.

I've written a program in python for my brother that searches the task list for a concrete process and if it doesn't find it, it runs it. His executable is a shortcut called x.lnk that resides in C:\

In python it looks like this:

os.startfile("C:\\x.lnk")

I want to rewrite the program in Ruby, but I'm having a hard time finding something that can run the shortcut. Can someone help?

Thanks

1 Comment
2020/03/04
13:37 UTC

4

Ruby newsletter that surfaces the old-but-good stuff

Hi all - hoping to get some feedback on a new side project.

Newsletters like Ruby Weekly have been really helpful for keeping up-to-date, but I often come across a well-written article and want more from that particular blog’s archives. Problem is, feeds only give you new stuff, to get the old-but-good stuff in their archives I have to manually sift through their blog.

todayilearn.dev is my attempt to scratch that itch - pick a few sources (there are currently 4), set the number of articles you want to get a day, and then wait to get something from their archives in your email inbox.

Would love to hear your thoughts - is this something you’d find useful? What other sources would you like to see?

0 Comments
2019/12/06
15:06 UTC

3

How do I review code? Like really review..help!

I’ve started learning ruby and have been lucky to pair with developers from different companies through several meet-up events. Through the process I’ve been encouraged to do code reviews. I’ve never done any before and have read lots of check lists but can’t actually picture what one would look like. One of the tasks given to me was to review a tic Tac toe game and provide a review in a pdf? I thought reviews were done through pull request and comments. Looking at the tic Tac toe game I feel being a beginner in Ruby my self the way the game was written makes sense to me and I can’t find anything wrong with it. Can anyone help? I can provide the code and if interested?

4 Comments
2019/11/14
10:57 UTC

2

How do you paste code snippets in a MS Word document?

So I am practising doing code reviews and have been asked to submit one in a PDF format. This may be a silly question but does anyone know how I can paste code snippets into MS word (using Mac)? I've looked all over and there are many suggesting using Open Document Text feature in Word but I dont have that on my MS word. Any one know a quick and simple fix?

2 Comments
2019/11/13
16:48 UTC

0

My scripts look like shell script that start with #!/bin/ruby

What's the typical workflow you use to leave that behind?

For instance, I would like to write a script that manipulates the efi partition files. I wrote it in (sh) shell script, but the string manipulation is easier/prettier in ruby.

I'm contemplating a little backup script which is more complicated because overstretching the resources is a factor. I know how to do that in /proc/ access but how (not really where) do I look that up in ruby object model.

5 Comments
2019/11/03
20:31 UTC

4

Magic Comments in Ruby

0 Comments
2019/08/31
08:26 UTC

Back To Top