How to combine next with puts "#{web_url.status[0].to_i} together and display it in console but only if if part is true.
tried:
next if ... && puts "{web_url.status[0].to_i}"
web_url = open(url, :proxy => BaseParser::PROXY, "User-Agent" => BaseParser.rand_ua_string() )
next if web_url.nil?
next if web_url.status[0].to_i == 410
next if web_url.status[0].to_i == 310
next if web_url.status[0].to_i == 404
next if web_url.status[0].to_i == 530
Here it is :
next puts "#{web_url.status[0].to_i}" if x == 2 # expression here
Example :
x = 1
until x > 3
next puts("#{x} matched"),x+=1 if x == 2
puts "this iteration has number #{x}"
x += 1
end
# >> this iteration has number 1
# >> 2 matched
# >> this iteration has number 3
Go through the documentation keywords.
Related
My code works perfectly on everything except 11, 12 and 13 or numbers that end in those last two digits.
def ordinal()
n = gets.chomp.to_i
suffix = n % 10
if suffix == 1
return "That's the #{n}st item!"
elsif suffix == 2
return "That's the #{n}nd item!"
elsif suffix == 3
return "That's the #{n}rd item!"
else
return "That's the #{n}th item!"
end
end
Any help would greatly appreciated! Thank you.
This is a special case. Check 2 digit suffix before you check 1 digit suffix. Something like this
def ordinal(n)
ending = case n % 100
when 11, 12, 13 then 'th'
else
case n % 10
when 1 then 'st'
when 2 then 'nd'
when 3 then 'rd'
else 'th'
end
end
"This is #{n}#{ending} item"
end
ordinal(1) # => "This is 1st item"
ordinal(10) # => "This is 10th item"
ordinal(12) # => "This is 12th item"
ordinal(15) # => "This is 15th item"
ordinal(112) # => "This is 112th item"
ordinal(123) # => "This is 123rd item"
could you help me out, please?
I want to write Ruby code in such a way that when I say the word "BYE!" 3 times in a row, it terminates the program.
My code is below
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
request = gets.chomp
while request != "BYE!"
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end
Any I could amend the code to follow the rules I want?
Check if this is what you want. and tell me if any error occurs. this may be the rough code
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
counter = 0
request = gets.chomp
while counter < 3
counter += 1 if request.eqls?("BYE!")
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end
puts 'If you type bye 3 times, this program will terminate'
bye_counter = 0
loop do
input = gets.chomp
if input == 'bye'
bye_counter += 1
else
bye_counter = 0
end
break if bye_counter == 3
end
I would do something like this:
quotes = File.readlines('quotes.db')
counter = 0
puts 'What?'
loop do
print '>'
request = gets.chomp
if request == 'BYE!'
counter += 1
break if counter >= 3
else
counter = 0
end
puts quotes.sample
end
Here is my attempt at writing Conway's Game of Life (http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Rules) in Ruby.
I have a very specific question about the "count_neighbours" method. Basically when I get to the edge of the grid I get some odd behaviour. When I parse Row 0 and reach the last column (Cloumn 4) it does something like this:
Evaluating cell: R: 0 C: 4
Evaluating neighbor R: -1 C: 3. State: 0
Evaluating neighbor R: -1 C: 4. State: 1
Evaluating neighbor R: -1 C: 5. State:
Evaluating neighbor R: 0 C: 3. State: 0
Evaluating neighbor R: 0 C: 5. State:
Evaluating neighbor R: 1 C: 3. State: 1
Evaluating neighbor R: 1 C: 4. State: 0
Evaluating neighbor R: 1 C: 5. State:
One good thing is that "R: -1" essentially wraps the evaluation around to the bottom of the grid as if the edges to the grid are really connected. I like the idea of an edgeless grid.
The bad thing here is that the method is trying to evaluate "C: 5" (Column 5) which doesn't exist because in this example the grid is columns 0-4. So that is the first problem I am seeking help to fix. Ideally here I want to evaluate column 0.
The next problem is when the method attempts to evaluate the last row on the grid, Row 4. When the method attempts to evaluate "R: 5" there is an error thrown. The error is "undefined method `[ ]' for nil:NilClass (NoMethodError)" because that row does not exist. To avoid the error being thrown I have added the line below the comment "#This line is a hack" but I want to be able to evaluate this row without an error.
The last question I have is, why does going beyond the last row to row 5 throw and error when going beyond the last column does not throw and error?
#Dimensions for the game grid
WIDTH = 5
HEIGHT = 5
def rand_cell
rand(2)
end
def starting_grid
#Initialise the playing grid
#start_grid = Array.new(WIDTH){Array.new(HEIGHT)}
#Randomly generate starting state for each cell on the grid
#start_grid.each_with_index do |row, rindex|
row.each_with_index do |col, cindex|
#start_grid[rindex][cindex] = rand_cell
end
end
end
def next_grid
#build the next generation's grid to load values into
#next_gen_grid = Array.new(WIDTH){Array.new(HEIGHT)}
#parse each cell in the start grid to see if it lives in the next round
#start_grid.each_with_index do |row, rindex|
row.each_with_index do |col, cindex|
puts "\n\nEvaluating cell: R: #{rindex} C: #{cindex}"
#next_gen_grid[rindex][cindex] = will_cell_survive(rindex, cindex)
end
end
#move the newly generated grid to the start grid as a sterting point for the next round
#start_grid = #next_gen_grid
end
def show_grid(grid)
#Display the evolving cell structures in the console
grid.each_with_index do |row, rindex|
row.each_with_index do |col, cindex|
if grid[rindex][cindex] == 1
print "️⬛️ "
else
print "⬜️ ️"
end
end
puts "\n"
end
end
def count_neighbours(row, col)
cell_count = 0
rows = [-1, 0, 1]
cols = [-1, 0, 1]
rows.each do |r|
cols.each do |c|
#ingnore the cell being evaluated
unless c == 0 && r == 0
#This line is a hack to stop an error when evaluating beyond the last row
if row != HEIGHT-1
puts "Evaluating neighbor R: #{row+r} C: #{col+c}. State: #{#start_grid[(row+r)][(col+c)]}"
if #start_grid[(row+r)][(col+c)] == 1
cell_count += 1
end
end
end
end
end
puts "Neighbour count is #{cell_count}"
return cell_count
end
def will_cell_survive(rindex, cindex)
count = count_neighbours(rindex, cindex)
#If the cell being evaluated is currently alive
if #start_grid[rindex][cindex] == 1
#test rule 1
if alive_rule1(count)
puts "Rule 1"
return 0
#test rule 2
elsif alive_rule2(count)
puts "Rule 2"
return 1
elsif
#test rule 3
puts "Rule 3"
return 0
end
#If the cell being evaluated is currently dead
else
#test rule 4
alive_rule4(count)
puts "Rule 4"
return 1
end
end
def alive_rule1(neighbour_count)
neighbour_count < 2
end
def alive_rule2(neighbour_count)
neighbour_count == 2 || neighbour_count == 3
end
def alive_rule3(neighbour_count)
neighbour_count > 3
end
def alive_rule4(neighbour_count)
neighbour_count == 3
end
#Run just one round of the game
system "clear"
starting_grid
show_grid(#start_grid)
puts "\n\n"
next_grid
show_grid(#next_gen_grid)
#Initiate the game grid
# system "clear"
# starting_grid
#Run the game
# 200.times do |t|
# system "clear"
# puts "\n\n"
# next_grid
# puts "Grid #{t}"
# show_grid(#next_gen_grid)
# sleep(0.25)
# end
[EDIT]: The code with the answer implemented is at https://github.com/AxleMaxGit/ruby-conways-game
If you want to connect the edges to each other (which by the way creates a "torus" shape, or if you prefer is the "asteroids" world model where you can never leave the screen) then the simplest adjustment is to work in modular arithmetic:
Change:
if #start_grid[(row+r)][(col+c)] == 1
To:
if #start_grid[(row+r) % HEIGHT][(col+c) % WIDTH] == 1
The operator symbol % is modular arithmetic, and does the wrap-around logic precisely as you need it.
The reason why going beyond the last row behaves differently to going beyond the last column is because:
#start_grid[ 3 ][ 5 ] == nil
which returns false in your check for neighbour, and everything else works as normal.
However,
#start_grid[ 5 ][ 3 ]
is a problem, because #start_grid[ 5 ] is nil, so it is effectively
nil[ 3 ]
the error is thrown because Ruby has no logic for resolving what [] means on a nil.
I keep getting the following error message:
text.rb:2:in `<main>': undefined method `choices' for main:Object (NoMethodError)
But I can't seem to understand why my method is "undefined":
puts "Select [1] [2] [3] or [q] to quit"; users_choice = gets.chomp
choices(users_choice)
def choices (choice)
while choice != 'q'
case choice
when '1'
puts "you chose one!"
when '2'
puts "you chose two!"
when '3'
puts "you chose three!"
end
end
end
This is because you are calling method choices, before defining it. Write the code as below:
puts "Select [1] [2] [3] or [q] to quit"
users_choice = gets.chomp
def choices (choice)
while choice != 'q'
case choice
when '1'
break puts "you chose one!"
when '2'
break puts "you chose two!"
when '3'
break puts "you chose three!"
end
end
end
choices(users_choice)
I used break, to exit from the while loop. Otherwise it will create an infinite loop.
def main
puts "Select [1] [2] [3] or [q] to quit"; users_choice = gets.chomp
choices(users_choice)
end
def choices (choice)
while choice != 'q'
case choice
when '1'
puts "you chose one!"
break
when '2'
puts "you chose two!"
break
when '3'
puts "you chose three!"
break
end
end
end
main
The method only needs to be called prior to being executed. Here I wrap the definition in the main method, but only call main after the definition of choices().
I was getting the same error running Ruby in Eclipse working out the App Academy practice exercises. I forgot to add "object." to the supplied test cases. The following syntax works:
#!/usr/bin/ruby
class Prime
# Write a method that takes in an integer (greater than one) and
# returns true if it is prime; otherwise return false.
#
# You may want to use the `%` modulo operation. `5 % 2` returns the
# remainder when dividing 5 by 2; therefore, `5 % 2 == 1`. In the case
# of `6 % 2`, since 2 evenly divides 6 with no remainder, `6 % 2 == 0`.
# More generally, if `m` and `n` are integers, `m % n == 0` if and only
# if `n` divides `m` evenly.
#
# You would not be expected to already know about modulo for the
# challenge.
#
# Difficulty: medium.
def primer(number)
if number < 2
return false
end
i = 10
while i > 1
if number > i && number != i
if number % i == 0
return false
end
end
i -= 1
end
return true
end
end
object = Prime. new
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts("\nTests for #primer")
puts("===============================================")
puts('primer(2) == true: ' + (object.primer(2) == true).to_s)
puts('primer(3) == true: ' + (object.primer(3) == true).to_s)
puts('primer(4) == false: ' + (object.primer(4) == false).to_s)
puts('primer(9) == false: ' + (object.primer(9) == false).to_s)
puts("===============================================")
Following the tutorial Zed A. Shaw, I'm writing a soccer game. My code so far is as follows:
$team_a_players = ["Basar", "Mehmet", "Abdullah", "Alpaslan", "Salih", "Recep", "Ibrahim", "Orhan", "Hakki", "Yakup", "Serdar"]
$team_a_substitutes = ["Hasan", "Turgay", "Umit"]
$team_b_players = ["Habib", "Erkan", "Sahin", "Cemal", "Ahmet", "Fikret", "Yucel", "Pergel", "Ali", "Sabri", "Yilmaz"]
$team_b_substitutes = ["Abdulkadir", "Gokhan", "Mustafa"]
$yellow = []
$red = []
$reasons = ["corner", "direct attack", "free kick", "side attack", "speed kick"]
$team_a_attack = 90.0
$team_a_defense = 80.0
$team_b_attack = 70.0
$team_b_defense = 60.0
$team_a_goals = 0
$team_b_goals = 0
def prompt()
print "> "
end
def dice()
if rand(2) == 0
round_team_a()
else
round_team_b()
end
end
def fauls()
if rand(0) > 0.95 and rand(10) % 2 == 0
faul_player = $team_a_players[rand(11)]
if $yellow.include?(faul_player)
$red.push(faul_player)
$team_a_players.delete("faulplayer")
puts "#{faul_player} of Team A gets a red card in #{$i}. minute!"
puts "Who would you like to substitute in place of #{faul_player}?"
list_subs_a()
prompt()
substitute = STDIN.gets.chomp()
$team_a_players.push("substitute")
$yellow.delete(faul_player)
else
$yellow.push(faul_player)
puts "#{faul_player} of Team A gets a yellow card in #{$i}. minute!"
end
elsif rand(0) > 0.95 and rand(10) % 2 == 1
faul_player = $team_b_players[rand(11)]
if $yellow.include?(faul_player)
$red.push(faul_player)
$team_b_players.delete("faulplayer")
puts "#{faul_player} of Team B gets a red card in #{$i}. minute!"
puts "Who would you like to substitute in place of #{faul_player}?"
list_subs_b()
prompt()
substitute = STDIN.gets.chomp()
$team_b_players.push("substitute")
$yellow.delete(faul_player)
else
$yellow.push(faul_player)
puts "#{faul_player} of Team B gets a yellow card in #{$i}. minute!"
end
else
faul_player = nil
end
end
def list_subs_a()
$team_a_substitutes.each {|p| puts p}
end
def list_subs_b()
$team_b_substitutes.each {|p| puts p}
end
def list_yellow()
$yellow.each {|p| puts p}
end
def list_red()
$red.each {|p| puts p}
end
def round_team_a()
score = $team_a_attack / $team_b_defense * rand(0)
if score > 1
goal = 1
$team_a_goals += 1
reason = $reasons[rand(5)]
puts "Team A scored #{goal} goal through a #{reason} in #{$i}. minute!"
else
goal = 0
end
end
def round_team_b()
score = $team_b_attack / $team_a_defense * rand(0)
if score > 1
goal = 1
$team_b_goals += 1
reason = $reasons[rand(5)]
puts "Team B scored #{goal} goal through a #{reason} in #{$i}. minute!"
else
goal = 0
end
end
def match()
$i = 0
until $i > 59 do
dice()
fauls()
$i += 1
end
puts "Team A scored a total of #{$team_a_goals} goals and Team B scored a total of #{$team_b_goals} goals."
if $team_a_goals > $team_b_goals
puts "Team A won against Team B by #{$team_a_goals}:#{$team_b_goals}!"
elsif $team_b_goals > $team_a_goals
puts "Team B won against Team A by #{$team_b_goals}:#{$team_b_goals}!"
else
puts "It's a tie!"
end
if $yellow.length > 0
puts "Players shown a yellow card are:"
list_yellow()
else
puts "No yellow cards in the end of the game"
end
if $red.length > 0
puts "Players shown a red card are:"
list_red()
else
puts "No red cards in the end of the game"
end
end
match()
From here, I would like to do the following:
Replace the arrays $yellow and $red with hashes so that I can also report minutes and teams of yellow- and red-cards.
Replace the arrays starting with the name $team_ with hashes so that I can add individualized attack- and defense-powers to players so that substitutions mean sth. but before the code gets any more complex, I have to solve sth. This looks similar to this question concerning php.
Define the functions list, round and faul in a way that can be used common to a_players and b_players . I tried doing team_#{team}_players instead of team_a_players etc, but cannot achieve it.
What I seek is a guide to that problem, not a solution, so that I can fix this myself. A link or long explanation in clear words is very much more welcome than a fixed code. And please note that the tutorial has not mentioned classes yet, so this is not an option yet.
The basic idea you haven't seemed to grasp is passing arguments to functions.
Assume we have two global variables and we wish to perform identical operations on them - say multiply elements of arrays by 2.
You write:
$a = [1,2,3]
$b = [2,3,4]
def multiply_a
result = []
for element in $a do
result << element * 2
end
result
end
def multiply_b
result = []
for element in $b do
result << element * 2
end
result
end
But this code is very bad. First of all, you should note that in Ruby $a is a special variable - a global variable. You should never need to use them - writing code containing them means that there is something wrong with it. So how to fix it?
The basic idea is to pass an argument to a function, instead of hard coding the variable, the function operates on. So you can transform the code as follows:
a = [1, 2, 3]
b = [2, 3, 4]
def multiply(argument)
result = []
for element in argument do
result << element * 2
end
result
end
# and then call
multiply(a) # instead of multiply_a
multiply(b) # instead of multiply_b
This is the way you should fix your code.