r/learnruby • • Feb 01 '19

New to Ruby question (Beginner)

6 Upvotes

I've started learning Ruby . I am starting with Code Academy to get the syntax down. I'm on the chapter, putting the form in formatting. I wanted to go over some code and try to write down what it means. Let me know if I'm correct or what I got wrong.

Print "what's your name?"
first_name = gets.chomp
first_name2 = first_name.capitalize 
first_name.capitalize!

=begin
1. Print basically prints the string, what's your name on the console
2. first_name is the variable you assign to gets. gets is just asking for input. .chomp is the method eliminating a blank line.
3. first_name2 is first_name but with the first letter capitalized? This is so that you have 2 separate variables in case you needed the original first_name elsewhere?
4. The method .capitalize! The confusing part. The ! basically throws away the original non-capitalized version and replaces it with the capitalized version maintaining the original variables formatting?
5. They wanted me to do some inputs for first name, last name, city, state. Then have them capitalized and then the input printed out on the screen.
=end

print "What\'s your first name?"
first_name = gets.chomp
first_name2 = first_name.capitalize
first_name.capitalize!

print "What\'s your last name?"
last_name = gets.chomp
last_name2 = last_name.capitalize
last_name.capitalize!

print "What city do you live in?"
city = gets.chomp
city2 = city.capitalize
city.capitalize!

print "Use Abbreviations. What state do you live in?"
state = gets.chomp
state2 = state.upcase
state.upcase!

puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}."

r/learnruby • • Jun 04 '18

Founder of MentorCruise here. I can help you to find a Ruby Mentor to advance/start your career!

Thumbnail
mentorcruise.com
6 Upvotes

r/learnruby • • May 04 '18

IDE for Ruby

6 Upvotes

What is the best IDE for working with Ruby? I have been using Atom and MS Code on Ubuntu and while both are functional, it seems like they are missing something. If these are the best tools for Ruby, what extensions and configurations do you suggest?


r/learnruby • • Apr 27 '18

30 Days of Code: Day 2: Operators

6 Upvotes

Problem

Today's problem involves reading in three quantities

  • the cost of a meal (e.g. 12.00) written as a dollar amount followed by cents with a decimal point in between (no dollar sign, or other units are used). It could be any other currency that has similar notation.

  • tip percent (e.g. 20) as an int

  • tax percent (e.g. 8) as an int

Figure out the total cost of the meal rounded to the nearest dollar and print a message.

Step 1: Read in input

Like the last problem, we'll read in the input, and convert the first to a float, the second and third to an int.

meal_cost = gets.strip.to_f
tip_percent = gets.strip.to_i
tax_percent = gets.strip.to_i

Recall that when the function gets is called (run, executed, etc), the program pauses to wait for user input. When the user hits Enter, the characters typed in (plus a newline) are sent back as a string.

Let's take a closer look at:

 gets.strip.to_f

gets produces a String as a result. The dot after it means to apply the method (or function) after the dot to the result before the dot. strip takes a String, and creates a new String with white space in the front and end and removes the white space. White space is defined as tab, a blank space, and newline. So if you had a string like ' \tthe cat \n' (where \t represents a tab), then resulting (new) string after calling strip is 'the cat'. There are spaces in the middle, but strip only removes spaces from the front and back. Note that it does not alter the string, but creates a new string.

The result of strip is a string, and to that string, we apply the method after the dot, which is to_f which converts the string, say, "12.00" into a float, i.e., 12.00 (or equivalently, 12.0). We use a float to approximate currency. It's not necessarily the best choice.

We do similar steps to read user input for the tip_percent and the tax_percent.

**Step 2: Compute the cost

Now we compute the tip and tax.

 tip = meal_cost * (tip_percent * 0.01)
 tax = meal_cost * (tip_percent / 100.0)

The computations are a little tricky. First, we see that programming languages (including Ruby) use the asterisk to indicate a multiplication. Second, Ruby uses / to indicate division.

The first tricky part is the tip is not: meal_cost * tip_percent. Since the tip_percent is 20, we'd multiply the meal cost (which is 12.00) by 20, and get 240.00 in tip. Much more than we expect to spend. 20 percent really means multiply by 0.20. One way to get 0.20 is to multiply the percent by 0.01, which is what we do.

tip = meal_cost * (tip_percent * 0.01)

Now, this looks like a formula, as if we define tip to be a function that multiplies meal cost to tip percent to 0.01. In Excel, if we did something similar, any change in the variables would cause tip to change.

This is NOT the case in most programming languages.

Instead, what happens is Ruby plugs in the current values of meal_cost and tip_percent and computes a value on the right hand side.

Thus,

 meal_cost * (tip_percent * 0.01) -> 12.00 * (20 * 0.01)
                                  -> 12.00 * 0.2
                                  -> 2.40

The arrow means "evaluates to". When Ruby sees an expression, it tries to compute a value. Evaluating an expression means computing a value.

The first step is plugging in the current values for variables. In this case, the current value of meal_cost is 12.00 and the current value of tip_percent is 20. Then, Ruby performs the math and eventually produces 2.40, which is the tip. This value is then saved to the variable, tip. Or more precisely, 2.40 is a float object with an object ID, and the object ID is saved to the variable tip.

Another way to compute the percent is to divide by 100. However, this is tricky. What do you think you get when you do 20 / 100. Math would say you should get 0.2 as a result. However, if you do this in Ruby, you'll get 0. That's because the left operand (the value left of the /) is an int. The right operand is also an int. When you divide and int by an int, you are performing integer division. This is equivalent to doing a division, and throwing away the fractional part (or remainder). Thus, 20 / 100 is 0 with a remainder of 20 (or it's 0.2). Chopping off the remainder or fraction leaves us with 0.

If you do 250 / 100, this is 2 remainder 50 or 2.5. Throw away the remainder or fractional part, and you're left with 2. It may seem silly to have integer division, but it does come in handy.

So, if you want a value that what you expect, then one of the numbers must be a float. That's why we write

 tax_percent / 100.0

The 100.0 is a float (tax_percent is an int). When you do division where one operand is a float, then Ruby performs a float division (which preserves fractions...to an extent).

So that's the next line of Ruby code

 tax = meal_cost * (tax_percent / 100.0)

Finally, we add up the total

total = meal_cost + tax + tip

Then we print out the cost

puts "The total meal cost is #{total.round} dollars."

The only new part is the #{}. If the string is double-quoted (as this is), then when Ruby sees a hashtag, followed by an open brace, then a Ruby expression, then a close brace, Ruby computes what's inside the two braces, and substitutes it into the string. This is called string interpolation. This doesn't happen with single quoted strings.

In it, total is 15.36. But then we apply the method round which can be applied to float values to round it. This gets rounded to an int, namely, 15. Thus, the resulting string, after string interpolation looks like

The total meal cost is 15 dollars.

The entire program

meal_cost = gets.strip.to_f
tip_percent = gets.strip.to_i
tax_percent = gets.strip.to_i

tip = meal_cost * (tip_percent * 0.01) 
tax = meal_cost * (tax_percent / 100.0)
total = meal_cost + tip + tax

puts "The total meal cost is #{total.round} dollars."

Normally, I would multiply by 0.01 for the tax_percent as well, but I wanted to demonstrate division as well as integer division.


r/learnruby • • Apr 26 '18

30 Days of Code: Day 1: Data Types

6 Upvotes

Sorry, Hello World was Day 0. Guess we programmers love to start at 0.

Let's start with a problem. Initially, three variables are given initial values;

i = 4
d = 4.0
s = 'HackerRank '

We'll read three more values from user input. The first will be an integer. The second will be a float. The third will be a String. We'll add the two integers (the one read in, and the one at the beginning) and print it, add the two floats and print it, and "add" the two strings, and print it.

From the prereqs post, we looked at three types, int, float, and strings. So, here they are again.

So far, we've only read user input using gets, which always returns a string. It turns out you can't do math with strings. For example, suppose you have

x = 3 + "4"

What happens? In an assignment statement (the = is called the assignment operator), you perform the computation on the right. The result is placed in the variable on the left (or more accurately, the computation produces an object with an object ID, and the object ID is stored in the variable x).

However, in Ruby, you can't add an integer to a String. This is called a runtime error. That is, the error occurs as you run the program. Other languages (say, Java) permit an integer to be added to a String. To do this, Java creates a new String object from the int (short for integer), i.e. "3", then does a form of string addition (which we'll talk about soon) to get a result.

So, when we read a int but it appears as a String, we need to convert it to an int. Ruby has functions (also called methods) to do this.

Let's see how this works. First, we'd normally write:

 i2= gets

This would read one line of user input, and store the string (or its object ID) into the variable, i2. But, we can want to convert it to an int first. Here's how to do it.

i2 = gets.to_i

On the right side, you see gets followed by a period followed by to_i. gets produces a string. The dot performs the operation on its right to that string. So, if the string were "21", applying to_i (which stands for "to integer") converts that string to an integer. So, an int object gets created and it has an object ID, and the string object that came from gets disappears (shortly thereafter) since it wasn't saved to a variable.

Let's look at to_i more carefully. Suppose you wrote:

  val = "  12  30  ".to_i

to_i processes the string by skipping over the spaces on the left, and reading the largest integer it can. First it sees 1, then it sees 2. Then it sees a space. At this point, it has seen "12" and that's the "largest" contiguous set of digits it can find. The space stops the processing, and the rest of the string is ignored. val then stores the object ID for the int, 12.

So, we write

 i2 = gets.to_i
 f2 = gets.to_f
 s2 = gets.rstrip

Note that to_f takes a string as input and produces a float object as output.

For the last line, I could have just used gets, but I decided to take the string that gets returns from user input, then call rstrip on that string. What rstrip does is to remove all spaces on the right side.

If you had the following string " cat " and called rstrip on it, the result would be a new String object that looked liked " cat". Notice the first string had 3 spaces at the end, while the subsequent string has no spaces on the right. rstrip means "right strip" which takes a string and produces a new string with no spaces on the right. If the string didn't have any spaces on the right, then the resulting string would be equivalent to the original string.

Why did I do rstrip?

Turns out, when you type a number in, say,3.14, followed by enter, the resulting string is "3.14\n". That is, it's the number you typed in and ends with a newline character. rstrip removes whitespace which is usually defined as a blank space (space bar), a tab, or a newline. It removes any combination of that from the right side. So I just wanted to remove the newline.

OK, so the program so far is

 i = 4
 d = 4.0
 s = 'HackerRank '
 i2 = gets.to_i
 d2 = gets.to_f
 s2 = gets.rstrip

Now we can print the "sum"

 puts i + i2
 puts d + d2
 puts s + s2

Operator overloading

Although you may think adding integers and adding numbers with fractional parts (floats) is the same thing, it's performed differently in hardware. Furthermore, how a computer stores 3 (an int) and how it stores 3.0 is different (and it isn't just the decimal point). I won't get into detail, but suffice it to say that a computer performs one kind of addition (int addition) when adding ints, and another kind of addition (float addition) when adding floats.

Ruby is "smart" enough (it's not a person, but whatever) to know which addition to use based on the type of the two values it is adding.

But what does it mean to add two strings?

String concatenation

Let's look at

 x = "cat"
 y = "dog"
 puts x + y
 puts x
 puts y

What does this do? In the third line, we have x + y. Since x andy store String objects, Ruby knows that + should mean do "string concatenation". This is a fancy word for putting two strings together, one right after the other. The result of x + y in the example above is "catdog".

Note that this creates a new string. In the fourth line, you'll see cat printed to the console. In Line 5, you'll see dog printed to the console on the next line. When the program runs, it looks like

 catdog
 cat
 dog

The original variables still refer to the original strings in x and y.


r/learnruby • • May 20 '17

learnruby: Daily Ruby snippets on Instagram

Thumbnail
instagram.com
6 Upvotes

r/learnruby • • May 28 '16

A Ruby basics course for kids and teens (x-post /r/ruby)

6 Upvotes

Hello,

We're Tech Rocket and we teach kids, teens and even adults the basics of programming and more. We just released a Ruby basics course today and would really love some feedback from this subreddit.

Now, before we go any further, if this is the wrong place to be posting this then please let us know! We really enjoy the feedback we get from Reddit. In the past we've received some really helpful comments on our Java and Python courses. Feel free to check out our account history.

It's free! The course is free. Yes, you have to create an account, but it takes less than a minute. We don't ask for payment information for our free accounts. They're 100% free. No strings attached.

The entire course is also only about 45 minutes. You'll laugh. You'll cry (okay you won't cry). You'll learn some stuff in the process.

We genuinely want your feedback and hope to continue to learn from subreddits like yours. Thank you and we hope you enjoy (and learn a lot) with the course.

Course Link:

https://www.techrocket.com/code/hour-of-code-on-tech-rocket-courses/ruby-basics


r/learnruby • • Feb 18 '16

Ruby REST Service Tutorial

6 Upvotes

Hey there!

I hope anybody can help me with this. This is my first time trying to build something in Ruby and I want to build a REST service in Ruby. I have never build any service like this before and I am fairly new to ruby (3 weeks now?).

So what I am looking for is a tutorial for a REST service that is very detailed. I want to build and understand what I am doing and what my application does. Unfortunately I could not find any good sources with google.

Does anybody of you have a tutorial that you would recommend?

Thanks in advance!


r/learnruby • • Jan 24 '16

Helping beginner rails devs

6 Upvotes

What has helped me improve in rails is to not only to code something every day but to read 1 or 2 posts or articles about rails every day. So I'd thought I'd start an email newsletter to help out beginners.

I recently started a rails daily newsletter to help beginners get more comfortable in rails and we have 180+ people signed up so far.

If anyone is interested in receiving a daily post or article that I've curated on rails, you can sign up here: http://www.yourrailsdaily.com/. You can view previous issues in the archive section of the website.

Hopefully you guys can find some value in these emails.


r/learnruby • • Nov 18 '15

Beginner problem with (very)simple code

6 Upvotes

Hi,

I just started to learn Ruby (my first programming language), and today I decide to make my second program which is Dice Roller. I don't have experience in programming, so it doesn't look well :P

  puts "How many times do you want to roll?"
choice = gets.chomp
puts "How many sides should dice have?"
sides = gets.chomp

c = choice.to_i
s = sides.to_i

c.times do
	puts rand(s) + 1
end

What I want to do, is print out how many times each number came up, but I can't figure out how to do this. I'm not looking for an answer, because I could find it myself, and probably learn nothing. All I ask, is some hint.

I'm thinking about using while, or to create Hash, and put values into it, then use sort method, but I'm not sure how to do that properly.

Also, I'm not sure if my code isn't too simple?

PS: Forgive me my poor english. This is another language, that I'm trying to learn.


r/learnruby • • Oct 05 '15

Should I learn Ruby ?

6 Upvotes

Hello everyone, recently I've been really interested by learning Ruby when I discovered the syntax and some of the famous projects running on this beautiful language.

I began some tutorials and now I'm going into some guides to Ruby On Rails. Until now everything is okay, I really like it. But the more I read some guides and discussions (and sometimes comparisons with other languages), the more I doubt on the lifetime of Ruby. I also read some articles about the creator and, wtf he is a mormon ??

Does this language tend to die already ? I can read here and there that Node.js is a serious competitor and now prefered by the developers. I think I should choose what I love first (and until now I love it) but I don't want to get involved into something that's going to be obsolete soon.

What's your opinion ?

Thanks in advance !

PS: Sorry, english is not my first language.


r/learnruby • • Sep 07 '15

Single white male seeking interactive JSON tutorial

6 Upvotes

I’m looking for some interactive tutorials to sink in JSON usage specifically in RoR.   I don’t mind paying for something if you know there’s a good one in some paid course.   Thanks for your help!


r/learnruby • • Jun 22 '15

Image Scraping Reddit

6 Upvotes

I'm trying to create something similar to this with Ruby as my first project. I've learned the basic syntax for Ruby and I'm decent with HTML/CSS/JS. The thing is I have no idea where to begin with something like image scraping and working with Reddit's API, etc. Any tips/suggestions would be appreciated. Thanks!


r/learnruby • • Sep 11 '14

First completed app. Feels like I'm not doing this "the Ruby way", looking for feedback.

6 Upvotes

This is part of my practice as I go through Learn Ruby the Hard Way. Exercise 36 is to go off and create a game, working on it for a week or so.

The code below feels sloppy, especially for the reason that I'm passing the "player, monster, kills" variables through everything. Seems like there's probably a more "Rubyist" way to be doing some of this. Even just some pointers such as "Look into this technique" would be very helpful, thank you.

This is a simple game where the player chooses a name, is assigned HP, and has three simple choices as actions. As the user kills monsters, the game tallies kills and shows the number to the user after they die. The point is to kill as many as possible before dying. Thanks very much for any feedback!!

Edit: reworked a bit for some edge cases. Edit 2: reworked some more, added magic, leveling, and critical hit systems.

class Player
	attr_accessor :name, :hp, :shield, :xp, :level, :mp

	def initialize(name, hp, shield, xp, level, mp)
		@name = name
		@hp = hp
		@shield = shield
		@xp = xp
		@level = level
		@mp = mp
	end

	def self.level_up(player, kills)
		if player.xp >= 100 && player.level < 2
			puts "#{player.name} has leveled up!  Spells can now be cast!"

			player.level += 1
			player.mp += 30
			player.hp += 15
			player.xp = 0

			arena(player, kills)
		elsif player.xp >= 100
			puts "#{player.name} has leveled up!"

			player.level += 1
			player.mp += 30
			player.hp += 15
			player.xp = 0

			arena(player, kills)
		else
			arena(player, kills)
		end
	end

	def name
		@name
	end

	def hp
		@hp
	end

	def shield
		@shield
	end

	def xp
		@xp
	end

	def level
		@level
	end

	def mp
		@mp
	end
end

class Monster < Player
end

#Where spells are called from
module Spells
	#Checking if user has enough MP to cast spell
	def self.mp_check(player, monster, kills, req)
		req_mp = req
		if player.mp < req_mp
			puts "#{player.name} doesn't have enough MP!"
			action(player, monster, kills)
		else
		end
	end

	def self.heal(player, monster, kills)
		req_mp = 3
		Spells.mp_check(player, monster, kills, req_mp)

		player.mp -= req_mp
		amt = rand(3..10)
		player.hp += amt
		puts "#{player.name} has been healed by #{amt} HP!"
		action(player, monster, kills)
	end

	def self.fireball(player, monster, kills)
		req_mp = 5
		Spells.mp_check(player, monster, kills, req_mp)

		player.mp -= req_mp
		dmg = rand(5..10)
		monster.hp -= dmg

		if monster.hp >= 1
			puts "#{player.name}'s fireball burns the #{monster.name} for #{dmg} HP!"
			action(player, monster, kills)
		else
			puts "#{player.name} launches a mighty fireball at the #{monster.name}!"
			monster_death(player, monster, kills)
		end
	end

	def self.earthquake(player, monster, kills)
		req_mp = 8
		Spells.mp_check(player, monster, kills, req_mp)

		player.mp -= req_mp
		dmg = rand(5..15)
		monster.hp -= dmg

		if monster.hp >= 1
			puts "#{player.name}'s earthquake crushes the #{monster.name} for #{dmg} HP!"
			action(player, monster, kills)
		else
			puts "The ground violently lurches and cracks open beneath he #{monster.name}!"
			monster_death(player, monster, kills)
		end
	end
end

def prompt
	print "> "
end

def outline
	puts "********************************************"
end

kills = 0

#Where the player makes his choices.  Initial if-then checking for Shield status in order to display SP for user
def action(player, monster, kills)
	if player.shield >= 1 && player.level >= 2 #Show MP and SP if player is of adequate level
		outline
		puts "\tOur Hero: #{player.name} \(Lvl #{player.level}\) \:\: #{player.hp} HP \:\: #{player.mp} MP \:\: #{player.shield} SP" 
	elsif player.level >= 2
		outline
		puts "\tOur Hero: #{player.name} \(Lvl #{player.level}\) \:\: #{player.hp} HP \:\: #{player.mp} MP"
	elsif player.shield >= 1
		outline
		puts "\tOur Hero: #{player.name} \(Lvl #{player.level}\) \:\: #{player.hp} HP \:\: #{player.shield} SP"		
	else
		outline
		puts "\tOur Hero: #{player.name} \(Lvl #{player.level}\) \:\: #{player.hp} HP"
	end
		puts "\t \t \tvs"
		puts "\tEnemy: #{monster.name} \(Lvl #{monster.level}\) \:\: #{monster.hp} HP"
		outline

#rolling a d20 to see who takes a turn
	turn = rand(1..100)

	if turn <= 20
		monster_attack(player, monster, kills)
	else
		puts "What would you like to do?"
		puts "1. Attack!"
		puts "2. Defend!"
		puts "3. Run away!"
		#Give the player magic if they're at least level 2
		if player.level >= 2
			puts "4. Cast spell"
		else
		end

		prompt; action = gets.chomp
		
		if action == "1"
			attack(player, monster, kills)
		elsif action == "2"
			defend(player, monster, kills)
		elsif action == "3"
			flee(player, monster, kills)
		elsif action == "4" && player.level >= 2
			magic(player, monster, kills)
		else
			action(player, monster, kills)
		end
	end
end

def magic(player, monster, kills)
	puts "What magic would you like to cast?"
	puts "1. Heal"
	puts "2. Fireball"
	puts "3. Earthquake"
	prompt; magic = gets.chomp

	if magic == "1"
		Spells.heal(player, monster, kills)
	elsif magic == "2"
		Spells.fireball(player, monster, kills)
	elsif magic == "3"
		Spells.earthquake(player, monster, kills)
	else
		magic(player, monster, kills)
	end
end

#20% chance of monster attacking - this checks for a hit or a miss by the monster
def monster_attack(player, monster, kills)
	puts "The #{monster.name} attacks #{player.name}!"
	mscore = rand(1..20)

	if mscore >= 8
		monster_attack_success(player, monster, kills)
	else
		puts "The #{monster.name} misses with its attack!"
		action(player, monster, kills)
	end
end

#The monster was successful in the attack
def monster_attack_success(player, monster, kills)
	damage = rand(1..6) + monster.level

	#Handing damage, taking Shield Points into accounts
	if player.hp >= 1  && player.shield >= damage
		puts "#{monster.name} whomps #{player.name} for #{damage} HP, but #{player.name}'s shield absorbs it!"
		player.shield -= damage
	elsif player.hp >= 1 && player.shield >= 1
		puts "#{monster.name} whomps #{player.name} for #{damage} HP, but #{player.name}'s shield absorbs #{player.shield} damage!"
		player.hp -= (damage - player.shield)
		player.shield = 0
	elsif player.hp >= 1 
		puts "#{monster.name} whomps #{player.name} for #{damage} HP!"
		player.hp -= damage
	else
		puts "#{monster.name} slays #{player.name} with a wicked blow!"
		player_death(player, monster, kills)
	end

	if player.hp <= 0
		player_death(player, monster, kills)
	else
		action(player, monster, kills)
	end
end

#The user chose to attack, checking for hit or miss
def attack(player, monster, kills)
	puts "#{player.name} attacks!"
	pscore = rand(1..20)
	if pscore >= 9
		d6(player, monster, kills)
	else
		puts "#{player.name} missed with a wild swing!"
		action(player, monster, kills)
	end
end

#The user's attack was successful, now rolling for damage and death of monster
def d6(player, monster, kills)
	damage = rand(1..6)
	crit_hit = rand(1..100)

	#Determine if the player's attack lands a critical hit for a damage modifier of 1.5x
	if crit_hit <= 15
		puts "CRITICAL HIT!"
		damage *= 2
	else
		damage = damage
	end

	monster.hp -= damage

	if monster.hp >= 1
		puts "#{player.name} slices #{monster.name} for #{damage} HP!"
		action(player, monster, kills)
	else
		puts "#{player.name} slays #{monster.name} with a wicked blow!"
		monster_death(player, monster, kills)
	end
end

#User chose to defend - checking for max shield value of 5, adding SP if not.  Allows user to go above 5 on addition of SP.
def defend(player, monster, kills)
	if player.shield >= (5 + player.level)
		puts "#{player.name} already has maximum defense!"
		action(player, monster, kills)
	else
		player.shield += rand(1..3)
		puts "#{player.name} prepares their defenses!"
		action(player, monster, kills)
	end
end

#User chose to flee; small chance of flight.  If they lose roll, monster wins attack.
def flee(player, monster, kills)
	chance = rand(0..20)

	if chance >= 15
		puts "#{player.name} flees the battle!"
		arena(player, kills)
	else
		puts "Oh no!  The #{monster.name} blocks #{player.name}'s path and attacks!"
		monster_attack(player, monster, kills)
	end
end

#User has defeated the monster.  Kill is added to tally, user starts over again.
def monster_death(player, monster, kills)
	puts "#{monster.name} thrashes about for a bit before gurgling its last breath.  You win!"
	kills += 1

	if monster.name == "Griffin"
		player.xp += rand(5..30)
	else
		player.xp += rand(20..50)
	end

	Player.level_up(player, kills)
end

#User has been defeated.  User is shown how many kills they tallied.
def player_death(player, monster, kills)
	puts "#{player.name} has died at the hands of the mighty #{monster.name}."
	puts "Before dying, #{player.name} slew #{kills} foul beasts!"
	exit(0)
end

#Beginning of game, getting user information and rolling for HP.
def start(kills)

print '''
 ____  __.___.____    .____        _________ ___ ___ .______________
|    |/ _|   |    |   |    |      /   _____//   |   \|   __    ___/
|      < |   |    |   |    |      _____  \/    ~    \   | |    |   
|    |  \|   |    |___|    |___   /        \    Y    /   | |    |   
|____|__ ___|_______ _______ \ /_______  /___|_  /|___| |____|   
        \/           \/       \/         \/       \/                '''

	puts "\n\tKill as many monsters as you can before you die!"

	puts "\nAfter the collapse of the rebellion and being on the run for months, you have finally been captured.  You will be sent to the arena to fight to the death...your death. \nHow long can you last?"

	puts "\nWhat is your name, rebel?"
	prompt; pname = gets.chomp

	if pname.length >= 1
		player = Player.new(pname, rand(20..30), 0, 0, 1, 0)
		arena(player, kills)
	else
		start(kills)
	end
end

#Generating initial monster and sending user to action choices.
def arena(player, kills)

	outline
	puts "\n#{player.name} takes a breath, looks around the arena, and prepares for battle.\n \n"
	
	monster_type = rand(1..2)

	if monster_type == 1
		monster = Monster.new("Griffin", rand(10..30), 0, 0, (player.level + rand(0..2)), 0)
		puts "A mighty Griffin swoops down from above!\n"
		action(player, monster, kills)
	else
		monster = Monster.new("Cyclops", rand(20..30), 0, 0, (player.level + rand(0..2)), 0)
		puts "A huge Cyclops comes crashing into the arena!\n"
		action(player, monster, kills)
	end
end

start(kills)

r/learnruby • • Aug 27 '14

How did you self-teach yourself Ruby?

6 Upvotes

Also, are there tutors out there?


r/learnruby • • Mar 19 '14

The Ruby_Newbie Guide to Symbols

Thumbnail troubleshooters.com
6 Upvotes

r/learnruby • • Mar 17 '14

RubyMonk.com is a great primer for those coming from another language

Thumbnail
rubymonk.com
6 Upvotes

r/learnruby • • Oct 21 '21

Getting to ALL solutions of the n-Queens Problem

5 Upvotes

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!


r/learnruby • • Jul 07 '21

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

5 Upvotes

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?


r/learnruby • • Oct 09 '20

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

5 Upvotes

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


r/learnruby • • Sep 14 '20

Here is a list with a few job openings for ruby developers that auto-updates everyday. Maybe can help someone!

Thumbnail docs.google.com
5 Upvotes

r/learnruby • • Dec 06 '19

Ruby newsletter that surfaces the old-but-good stuff

5 Upvotes

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?


r/learnruby • • Mar 28 '19

What version of ruby should I be using?

5 Upvotes

So I'm just starting to use ruby and have been working through some practice problems and ran into an issue where a method I tried to use wasn't included in the version of ruby that I was using: 2.3.7. Thing is, I literally just installed ruby over the weekend so I would assume that if I'm not using the most current version of ruby then I'm using the most stable? I did some light googling on the subject, however I'm having a lot of trouble finding information that is current.


r/learnruby • • Jan 20 '19

"Roadmap to becoming a DevOps in 2019" by Kamran Ahmed, via GitHub.

Post image
5 Upvotes

r/learnruby • • Nov 23 '18

Ruby help with setting a variable's value if it hasn't already

5 Upvotes

I am using ruby to create a 'fact' for puppet and am struggling a little with the syntax for checking a variable.

The fact runs a powershell command to check the version of microsoft exchange, however this fact will be run on servers that may not have exchange installed and I would like to set a default variable of 0 if the command fails, but I am not 100% sure on how to check this.

If it helps, this is the current code:

Facter.add('microsoft_exchange_version') do
    confine :osfamily => :windows
    setcode do
    	powershell = 'C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe'
		command = 'Get-ExchangeServer | fl name,edition,admindisplayversion'
        exc_ver = Facter::Util::Resolution.exec(%Q{#{powershell} -command "#{command}"})
        if exc_ver.nil? 
            exc_ver = 0
        end
   end
end

Thanks!