Wayne Rumble Wayne Rumble - 2 years ago 97
HTML Question

Setting a default value to a blank form in html.(Ruby, Sinatra, CSS)

im very new to html and have a basic understanding and cant use java query or javascript yet. I am trying to give a player the option to fill in the player 2 name field to play a friend or leave it blank to play the computer in a basic game of rock, paper, scissors. I was hoping that if the field was left blank the param would pass nothing and the default value would be set in my Player Class.


<form id="name_form" action="/name" method="post">
<label for="name" id="name_label">Enter Player Name:</label>
<input type="text" id="player_name" name="name" >
<label for "name" id="name_label"> Second Player Name:</label>
<input type="text" id="player_name" name="name2" >
<input type="submit" value="Play!" id="play_button";>


class Player

attr_reader :name

def initialize name = "Computer"

@name = name




post '/name' do
player = Player.new params[:name]
player2 = Player.new params[:name2]
@game = Game.create player, player2
redirect '/play'

I was hoping something like the above would workbut i cant it to. Am i missing something? I would rather not use javascript yet. Thanks

Answer Source

params[:name] and params[:name2] have an empty string "" as a value. So, you are actually passing an empty string to your constructor. That's is "default value" is not used. If you want to use default value, then you have to omit an argument, like so:

# => #<Player:0x007f9c5116b698 @name="Computer">

Also, note, passing nil will still mean that you are passing an argument with the value of nil and default value will not be picked up

# => #<Player:0x007f9c5116b698 @name=nil>

That's why you need to update your code to this:

class Player
  attr_reader :name

  def initialize name
    @name = name.empty? ? "Computer" : name
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download