Showing posts with label variables. Show all posts
Showing posts with label variables. Show all posts

Sunday, October 23, 2011

Here documents in Ruby

I'm still working through Learn Ruby the Hard Way, and the last few exercises have been about building simple text based dungeons. You may recall I spent about a week working on one of my own. This latest exercise introduced me to here documents.

A here document is an easy way to display a long, multiline string. This would have been PERFECT for use in my dungeon adventure. Here's how it works.

This is the original description from the first room in the dungeon game I built:

  puts "This room is dimly lit by two sputtering torches."
  puts "There are three doors leading out of here."
  puts "What do you do?"

You may notice a few "puts" methods. It's not terrible in this case, since I'm putting several small statements, but it's tedious to type and unnecessary to use so many methods when you could do it with one here document. So forget what I said. There's a better, simpler way to do it, so it IS terrible!

So this example can be re-written like this:

  puts <<−TORCH_DESCRIPTION
  This room is dimly lit by two sputtering torches.
  There are three doors leading out of here.
  What do you do?
  TORCH_DESCRIPTION

You begin the here document with <<−TORCH_DESCRIPTION and end it with TORCH_DESCRIPTION. Ruby interprets everything in between as one string. Cleaner, right? Easier to read? Who wouldn't love it!

On a side note, you CAN write this as <<TORCH_DESCRIPTION instead, but by adding the minus sign, you can indent the code as usual. Without the minus sign, the terminator can't be indented, or else Ruby will start complaining about "can't find string TORCH_DESCRIPTION anywhere before EOF".

So I recommend using the minus sign. One more character makes your code a lot easier to read. I also ran into another little problem. Since a here document is a string literal, any variables won't be interpreted correctly. This is where interpolation comes into play. Here's an example from the current exercise I'm working through.

guess = gets.chomp()

if guess != good_pod
  puts "You jump into pod %s and hit the eject button." % guess
  puts "The pod escapes out into the void of space, then"
  puts "implodes as the hull ruptures, crushing your body"
  puts "into jam jelly."
return :death

This bit of code describes an escape pod room, where the user has to pick an escape pod to use. So we set the user's choice as "guess" and then call it in the method below. This is what happens when a user chooses poorly. However, if I were to rewrite the code using a here document, this is what I'd have:

  puts <<-BAD_POD
  "You jump into escape pod %s  and hit the eject button. %guess
  The pod escapes out into the void of space, then
  implodes as the hull ruptures, crushing your body
  into a jelly."
  BAD_POD
return :death

Now the %s and %guess won't be interpreted as variables, since they're inside of a string literal. Luckily, there's an easy solution: interpolation. Just swap out the %s for this little guy:

#{guess}

Ruby will look at this, understand that means you want to use a variable inside of a string literal, and then pull the information it collected when it asked the user which pod he wanted to jump into.

I'm hoping this post will be helpful for others who are grappling with here documents. It took me a bit of digging to figure out how to get the code to index properly (since it looked awful in Textmate, and my solution was to put the string in quotes, which was unnecessary) and I needed to figure out how to call a variable from inside the here document.

Monday, October 10, 2011

Scope issues with Ruby

I'm still working through Learn Ruby the Hard Way. The exercise I'm working on now has me building a text-adventure dungeon (similar to the one I made when I was going through Beginning Ruby) but this time around I've got a better idea of how to map the project out.

Basically I'm starting with a simple 4 room dungeon. Players will need to go to one room to get a key to unlock a door in the starting room. I understand how to build rooms and allow a player to navigate between them, but managing an inventory and allowing players to access different rooms once they have completed a specific action (such as finding a key to unlock the door) was confusing me.

After asking for some input on Stack Overflow, I think I've got a better handle on the problem now. I'd originally set door_open = false in the start_room method, then once a player had found the key in the chest_room method, I set door_open to true. However, I couldn't call this from the start_room, because it was a local variable. As far as start_room was concerned, door_open was still = false. Am I thinking about this the right way?

I'll simply make key into an instance variable, so it can be accessed by all methods, and edit the logic so while !@key_present, players can open the door. Easy enough! Just wish I could get to coding NOW instead of tonight.

Also, I've been using if/elsif statements, but the same user suggested case/when is cleaner and simpler. I haven't used case/when before, but from the snippet of code he posted, I think I agree. Your thoughts?

Wednesday, September 21, 2011

Instance variables and local variables in Rails

I've got a lot to learn about local and instance variables. I already knew 'character' meant a local instance of character, but I thought '@character' referred to another model, and not an instance of the Character model. I knew that sometimes if Rails was complaining about an unidentified local variable, putting an @ in front would often fix the problem, but I didn't know why. I think I've got a better handle on this, but I think the time has come to do some serious background reading to try and patch up some of the holes in what I know and what I think I know.

On the other hand, thanks to help from @jqr and a healthy does of trial and error, I've gotten that pesky statistic bonus problem figured out. This is what ended up working:

def total
  fortitude_base + character.statistic.con_modifier + magic + misc
end

And here's the con_modifier definition from my Statistic model:

def con_modifier
  (constitution.to_i - 10) / 2
end


I'm keeping it as .to_i now, as a fix for a case where a player tries to create a Fortitude save before a Constitution score has been entered. The .to_i translates a nil record to 0, so Rails does a temporary calculation (which isn't shown) rather than displaying an error. Not sure if there's a better way to handle this (perhaps simply checking that statistic.constitution.present? before performing any calculations) but it works for now.

More importantly than simply figuring this one instance of how to define logic in one model and then call it in the view of another is understanding HOW it works. I can extrapolate these methods and apply them to other things: skills, attack rolls, armor class, etc, etc. Once again, Manticore proves to be a useful learning tool! SUCCESS!

Tuesday, February 1, 2011

Syntax Issues in Ruby

Still working through Chapter 3 of Beginning Ruby. It's slow going because every time I get to an example (and there are lots of examples) I have to stop and do it, then run it to see what it does. Then I try to change the code around using what I already know. Sometimes this works. I'm actually surprised at how often I can predict what will work in Ruby.

Sometimes it doesn't work. Take this bit of code for example. All it does is check a string for vowels and returns a result.

This code is valid:

x = "The quick brown fox jumped over the lazy dogs."
puts "This string has vowels" if x =~ /[aeiou]/

This code is not valid:

x = "The quick brown fox jumped over the lazy dogs."
if x =~ /[aeiou]/ puts "This string has vowels"

I don't get why this doesn't work. All I've done is rearranged the bits of code. It's possible I need a bit more code to make this work this way and it's possible it just doesn't work this way. It's also possible I'm just getting ahead of myself (again) but I've never been able to learn something, even the basics of something, without wanting to mess around with it and see what else it could do.

Either way, the example from the book didn't use a variable. In place of x the book had "Test string" which still returns the same result, "This string has vowels" but is less useful because a variable is more useful. If this was a bit of code I was actually going to use for something, I could pull that variable from anywhere - a file, user input, etc. So I don't have a problem understanding variables, at least.