r/learnruby • • Dec 30 '14

Need some help with my first sudoku solver

1 Upvotes

https://eval.in/238165

So, as a Ruby virgin I thought I'd challenge myself somewhat today. And so I did. I wrote this peace of something I believe is quite bad coding in a few hours, trying to puzzle everything together and use whatever I've learnt from Codecademy. However, I'm not sure how to finish this. Can anyone please help? By the way, next version will be a class, when I've figured out why it should be a class.

Also, the save feature isn't fully implemented, so it just puts the rows to the screen, instead of saving them. I'm fully aware of that it uses a random number, but I'm still young, so I can wait and learn to code in the meantime.


r/learnruby • • Dec 06 '14

I could really use some help to break down a project (writing an executable) for work

3 Upvotes

I have been learning to program in Ruby and develop on the web for about 9 months. I have learned a lot from the free sources I've found on Reddit, and a few other places.

However, I hit kind of a wall. I need personal instruction, so I decided to go back to school for my associates in software development.

I mentioned to a few of the developers at work that I was learning to program, and they have been giving me pointers along the way, but I still have a lot to learn.

We have a meeting every morning to discuss the open projects list, and I had a feature that I'd submitted a request for the day before.

We keep records of traffic on each of our customers ( I work for a wholesale VoIP provider), and our customers have the ability to download the records in daily format, from our customer portal. One customer in particular emails every month, and requests the entire months call records be sent over, since she "doesnt have time to mess with it".

This is a fairly simple request to fulfill, so I typically oblige without protest. All I do is run a pretty basic select statement in SQL, and copy and paste the results in to an excel spreadsheet.

One of the admins noticed I was sending them after seeing the customers request, and asked me to submit the feature request, so the customer can set a date range to download the records, instead of only having the option for daily call records.

After a bit of back in forth in the meeting, it was decided that it was not worth it to change the current code to accommodate the customer, since it only takes me a few minutes a month to email them to her.

However, immediately after the meeting, the senior developer pulled me aside, and said "I bet it would go along way to show these guys that you want to program for real, if you wrote an executable that did that work for you."

I really believe I have learned enough to actually write it, or at least google until I get it figured out. The problem is, I dont really know where to begin. I don't know what would be involved in the process to make a sort of roadmap.

What Im hoping is that someone can help point me in the direction I need to be so I can give this thing a shot. Even if it doesnt work, if I show them what I did Im sure it would score me some major points.

TL;DR - Learning developer needs to know what steps would be involved in writing an executable program that would pull records from a SQL database, and export them to excel.

This could maybe even help get me a job in development when Im done with school, so any advice is greatly appreciated.


r/learnruby • • Nov 30 '14

Private method issue in IRB

1 Upvotes

This code works fine on Repl.it, but I get an error in IRB. Whats going on here?

2.1.1 :001 > def foo
2.1.1 :002?>   puts self
2.1.1 :003?>   end
 => :foo 
2.1.1 :004 > "bar".foo
NoMethodError: private method `foo' called for "bar":String

r/learnruby • • Oct 30 '14

Can't get variables to work in Powershell

0 Upvotes

Hi, I am following along the Learn Ruby the Hard Way book and I am having some trouble with Powershell. I have gotten Ruby running in the shell and I can perform calculations and run .rb files. However, when I try to do a simple variable assignment such as:

i = 4    

I get a large red error message saying something along the lines of "i : The term 'i' is not recognized as the name of a cmdlet, function, script file, or operable program etc..."

Why is it trying to read this as a script/program name instead of a variable assignment?

Using Ruby 2.0.0p576 (x64) on a 64 bit Windows 8 machine if that helps at all.

EDIT: I also realized that it won't allow me to even do basic comparisons like 4 == 9. It tries to read that as an assignment for some reason.


r/learnruby • • Oct 27 '14

Why does ruby re-order a defined hash?

1 Upvotes

I created a hash (below) and want to iterate through it from left to right. As you can see from the output, it's rearranged itself (and it doesn't appear to have a logical order). What's up with that?

change = {25 => 0, 10 => 0, 5 => 0, 1 => 0} 
p change
{5=>0, 1=>0, 25=>0, 10=>0}
=> nil

r/learnruby • • Oct 24 '14

Beginner practice on the go / over short amounts of time?

2 Upvotes

A little background: This is the last year of my undergrad (bio major) and I'm looking to get into Ruby. I'm in the super early stages of learning (Codeacademy/various tutorials). It's a lot of fun and I really enjoy it, but the biggest challenge is finding the time to do it every day because I have to prep for the next day each night. I am able to set aside 10-12 hours on the weekend, but I'd like to be more consistent throughout the weekdays.

I've tried listening to some audio tutorials while in lab or just thinking about what I learned, but the latter often becomes hard (I tend to be unsure of 60-70% of what I learned if I don't practice). If anyone has tips on how they practiced on the go or while eating (~45 minute or so breaks) I'm all ears. Unfortunately I don't have a laptop.

Thanks for the help!

tl;dr: Any tips on how to study/practice on the go over short periods of time (without a laptop)?

edit: I did a bit of looking around and found that maybe books that don't require a laptop/computer would be a good avenue. I really hate reading, but this is definitely something I'm interested in.

I read up some reviews on Well-grounded Rubyist and Eloquent Ruby; people said that both of these should not be an "intro" book. Would I be able to get through either of these after finishing the Codeacademy course? Any recommendations of which one to get?


r/learnruby • • Oct 14 '14

Point in Polygon Gem

2 Upvotes

I'm new to Ruby and learning as I go along, while working on a small personal project.

I want to input a geocoded point (lat & long), and return just the name of the map area it is in. I found a great gem that fits my needs almost perfectly over at GitHub, but have only been able to get it to return true and false.

https://github.com/square/border_patrol

In the documentation, I found some code that I believe should extract the 'placemark' in my KML file but I keep getting undefined methods.

Here is my code. I have multiple polygons, inside placemark parents in my KML file.

require 'open-uri'
require 'border_patrol'

kml_file = open("regionlist.kml")
region = BorderPatrol.parse_kml(kml_file)

userinput = BorderPatrol::Point.new(-122.5, 37.75)

region_area = region.contains_point?(userinput)
puts "Your point is in the region:", region_area

kml_data = File.read("regionlist.kml")
doc = Nokogiri::XML(kml_data)
polygon_node = doc.search('Placemark').first

placemark_name = BorderPatrol.placemark_name_for_polygon(polygon_node)

Much thanks for any help! I can make what I need work without this, but it would be nice to have a single KML where all the polygons are checked and the name of the 'point in polygon = true' being returned.


r/learnruby • • Oct 10 '14

Trying to break bad habits early - Chris Pine Roman Numeral Example

2 Upvotes

So for those familiar with the Chris Pine Learn to Program book, this was my attempt at the Roman Numeral example. Once I saw his two possible solutions it appeared that I went way overboard and didn't simplify enough. I was attempting to not repeat code to make it easier to adjust for the future, but I'm starting to think I just over thought the idea. Should I have simplified more or would this be considered acceptable by others? Thank you for your help.

Mine:

    def roman
    	puts 'Type a number'
    	take = gets.chomp.to_i
    	romannums = [['I', 1],['V',5],['X',10],['L',50],['C',100],['D',500],['M',1000]]
    	count = romannums.count - 1
    	while count >= 0
    		print (romannums[count][0] * (take / romannums[count][1]))
    		take = take % romannums[count][1]
    		count -= 1
    	end
    end

r/learnruby • • Oct 09 '14

Intermediate Ruby Tutorial

4 Upvotes

I'm a student with with some knowledge on the basic ruby sytanx and OOP principles...I'm looking to delving into intermediate to relatively advanced concepts and later on sinking my teeth to rails with a solid understanding of the underlying ruby language, how a framework works instead of just using it and how the web in general works.

Anyone know of any ruby tutorials that I can use to understand the following concepts...especially ones in which expound on a concept by working on a project rather than using a more theoretical approach

Skimming through TCP/IP
Understanding HTTP
Skimming through CGI
Understanding Rack
Understanding servers
Profiling various servers available for Ruby
Building a simple framework to serve web pages.


r/learnruby • • Oct 08 '14

Is this RoR SaaS course on edX the "best" MOOC available to learn Ruby?

Thumbnail edx.org
0 Upvotes

r/learnruby • • Sep 30 '14

Can you pass a variable from a block into another variable?

2 Upvotes

I'm doing a practice exercise (not homework) and I'm trying to compare each character in two strings. The hamming problem.

def compute(string1, string2)
    count = 0

    string1.each_char do |c|
    string2.each_char do |d|
    if c != d
      count ++
    end
  end
end
  return count
end

But I get an error: hamming.rb:10: syntax error, unexpected keyword_end hamming.rb:14: syntax error, unexpected end-of-input, expecting keyword_end

It looks like my 'end's match up. But even if that is just the problem, can I go about the problem this way?


r/learnruby • • Sep 29 '14

Anyone website with small ruby projects?

4 Upvotes

I just want to see some simple/small ruby projects that are done.. just to see/read and get a hang of Ruby more and to see how its all put together as a whole.


r/learnruby • • Sep 27 '14

I took a bunch of (basic) notes and want to share them with anybody that may benefit from them (x-posted from /r/learn programming)

11 Upvotes

r/learnruby • • Sep 25 '14

Ruby Wizardry (my Ruby book for kids) now in Early Access! (X-Post from r/ruby)

Thumbnail nostarch.com
3 Upvotes

r/learnruby • • Sep 23 '14

Help understanding class methods

1 Upvotes

I'm reading Why's Poignant Guide to Ruby. In Chapter 3 he mentions class methods. And gives this example:

Door::new( :oak )

As seen above, the new class method is most often used to create things. In the above example, we’re asking Ruby to make a new oak door for us. Of course, Ruby has to have an understanding of how to make a door—as well as a wealth of timber, lumberjacks, and those long, wiggly, two-man saws.

I don't understand what he means by class methods. Do you have to use the ':' symbol inside the () when using class methods?

Is this saying there's a class called Door that has a new method and we're passing it in 'oak'?

And we're creating this from a different class or file?

Is this the same thing as doing something like,

wood = "oak"
Door myDoor = new Door(wood)

in Java?


r/learnruby • • Sep 22 '14

Ruby Koans question

3 Upvotes

So I have never done the Ruby Koans. I decided why not lets do this maybe I'll learn some things I didn't know or at least get some practice to solidify what I already know. Now I already know that

hash=Hash.new("cat")  

creates a default if a key/value isn't explicitly given.
What I don't get is why:

hash = Hash.new([])

hash[:one] << "uno"
hash[:two] << "dos"  

creates an array with both values in both key bindings.


r/learnruby • • Sep 22 '14

Mastermind Game Question

1 Upvotes

I have two strings guess = 'rgby' code = 'gbyg'

How do I count the correct number of colors/characters guessed in the code? In this case the answer would be 3. The guess has 3 correct guesses contained in the code, irrespective of position.


r/learnruby • • Sep 16 '14

Trouble with scope in Ruby

3 Upvotes

Hi all,

I'm having some trouble understanding scope in ruby.

Here is a link to a repo if you'd like to download/run what I'm talking about to see for yourself:

https://github.com/minervadreaming/killshit

I have several .rb files present - specifically, I'm having an issue calling a class method from an instance. Seems like I'm not properly following scope, but I'm not sure how.

Here is a snippet from room.rb:

module KillShit
	class Room
		attr_reader :player, :monster, :game

		def initialize(player, monster, game)
			@player = player
			@monster = monster
			@game = game
		end

		def action
			outline
			Player.describe(player)
			vs
			Monster.describe(monster)
			outline

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

			if turn <= 20
				monster_attack
			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.maglevel >= 1
					puts "4. Cast spell"
				else
				end

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

		def magic
			puts "What magic would you like to cast?"
			if player.maglevel == 1
				puts "1. Heal"
				puts "2. Fireball"
				puts "3. Tremor"
				prompt; magic = gets.chomp

				if magic == "1"
					Spells.heal(player)
				elsif magic == "2"
					Spells.fireball(player, monster)
				elsif magic == "3"
					Spells.tremor(player, monster)
				else
					magic
				end
			elsif player.maglevel == 2
				puts "1. Greater Heal"
				puts "2. Firestorm"
				puts "3. Earthquake"
				prompt; magic = gets.chomp

				if magic == "1"
					Spells.greaterheal(player)
				elsif magic == "2"
					Spells.firestorm(player, monster)
				elsif magic == "3"
					Spells.earthquake(player, monster)
				else
					magic
				end
			else
			end
		end
	end
end

As you can see, when the player chooses to cast a spell it calls out to a Spells class, which I have in spells.rb. Here is a snippet from that code:

require_relative 'room'
require_relative 'player'
require_relative 'monster'

module KillShit
	class Spells
		attr_accessor :player, :monster

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

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

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

The problem is in the "Room.action" call at the end of the self.heal method (or just "action" as was my first attempt, as can be seen in the self.mp_check method). When it is hit, the following error is received:

spells.rb:27:in `heal': undefined method `action' for KillShit::Room:Class (NoMethodError)

I thought that it might've been because I needed to define "action" as a class method with "self." but that isn't doing it.

Any ideas? What should I be reading up on to better understand the concept behind what's happening here?

Thanks!


r/learnruby • • Sep 13 '14

How do API wrappers utilize instance methods?

2 Upvotes

I wasn't sure how to phrase the title, but I'm learning how to write a good API wrapper right now. Design and implementation, really.

I keep seeing method chaining that looks like this:

client.users.show? :screen_name=>'some_user' #http://twitter.com/users/show.json?screen_name=some_user

Taken from https://github.com/hayesdavis/grackle

Which is neat but I'm unsure how that users method is defined. I don't see a method definition for users. How are those chains built because I see that style everywhere but I can't figure out how they're doing it.

I'm only really familiar with segregating code responsibilities using modules and classes so I'd have something like this:

list_o_users = Client::Users.search('query')

or

user = Client::Users.new list_o_users[0]

Or something like that.

Let me know if anymore information is needed. I'm not sure what the technical terms would be for building those method chains.

Any and all help is appreciated.


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 • • Sep 11 '14

Trouble understanding how to access class instance variables from a method

3 Upvotes

Hi all,

Let's hop right to it! Here is a code snippet:

class Player
	attr_accessor :name, :hp

	def initialize(name, hp)
		@name = name
		@hp = hp
	end

	def name
		@name
	end
end

def prompt
	print "> "
end

prompt; pname = gets.chomp
player = Player.new(pname, rand(20..30))

puts "#{player.name} \:\: #{player.hp} HP"

def test
	puts "#{player.name} \:\: #{player.hp} HP - IN METHOD"
end

test

The output I receive is:

$ ruby wtf.rb

> Test Name

Test Name :: 20 HP

wtf.rb:24:in `test': undefined local variable or method `player' for main:Object (NameError) from wtf.rb:27:in `<main>'

So, my question is - why does my call to player.name work in the first instance, and not from within my method?

Thanks!


r/learnruby • • Sep 08 '14

Question about implicit and explicit block conversion.

5 Upvotes

Doing the rubymonk.com tutorials, and something came up that doesn't make much sense to me. In the explicit / implicit section (https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/18-blocks/lessons/55-new-lesson) they have this bit of code:

def calculation(a, b)

  yield(a, b)


addition = lambda {|x, y| x + y}

puts calculation(5, 5, &addition)

As I understand it, the ampersand before addition is used to convert an implicit block into an explicit block (or in other words, a proc), but isn't addition already of the class proc when addition = lambda {|x,y| x+ y} is defined? Seems redundant to me. Thanks.


r/learnruby • • Sep 05 '14

Python has very "pythonic" ways to solve problems. Does Ruby have "Rubaic" ways to solve problems?

1 Upvotes

I'm a python man. I love, eat, sleep and breathe python3.x. I mainly used it to data-mine. Recently, an internship opportunity has required me to learn the ways of Ruby.

My question now is this: Is there a "right" way to solve problems. Especially problems related in the field of webscraping?

Anyways, that's really it. Thanks for helping out!


r/learnruby • • Aug 30 '14

Chicago suburb area learning Ruby?

3 Upvotes

I checked on meetup.com if there is any Ruby meetups near my area and yes there is, but I wanted more of a specific meetup where tutors/rubyist lovers who are willing to help beginners like me to learn Ruby hands on. Is there such thing as this? I am from around the Elmhurst area and willing to travel as far as Glen Ellyn/Naperville area as well. Just trying to see if there's any opportunities out there that I do not know of...


r/learnruby • • Aug 27 '14

How did you self-teach yourself Ruby?

6 Upvotes

Also, are there tutors out there?