Dynamically create variables in ruby [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was hoping something like this would work:
while i < 3 do
puts i
#b[i] = Benchmark.new
i += 1
#a += 1
end
puts "Here is a #{#a}"
puts #b0.inspect
puts #b1.inspect
puts #b2.inspect
Sadly, it doesn't work at all. []= is regarded as an unrecognised method!

You can also use instance_variable_set
3.times{|i| instance_variable_set "#x#{i}", i }
#x1 # => 1
#x2 # => 2
Though for this particular task you should use arrays, it's a rookie mistake to use lots of variables instead of lists.
benchmarks = []
n.times { benchmarks << Benchmark.new } # or benchmarks = (0..n).map { Benchmark.new }
benchmarks.each do |bm|
# do stuff
end

This is clearly a job for an array, not for many instance variables.
benchmarks = number.times.map { Benchmark.new }
puts "Here is a #{number}"
benchmarks.each { |b| puts b.inspect }

Answered my own question! The eval method is the answer:
puts "Welcome to Benchmark 1.0! How many benchmarks do you wish to perform? (We recommend three)"
number = gets.chomp.to_i
#a = 0
i = 0
while i < number do
puts i
eval("#b#{i} = Benchmark.new")
i += 1
#a += 1
end
puts "Here is a #{#a}"
puts #b0.inspect
puts #b1.inspect
puts #b2.inspect

Related

How to exclude an unused case by conditions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Which is better?
string.each_char do |letter|
unless letter == " "
if letters.has_key?(letter)
letters[letter] = letters[letter].next
else
letters[letter] = 1
end
end
end
or
string.each_char do |letter|
if letter == " "
elsif letters.has_key?(letter)
letters[letter] = letters[letter].next
else
letters[letter] = 1
end
end
It seems awkward to leave an if statement without the body, but it also seems preferable to going a step deeper with unless.
There's a better way to write this code. I didn't know about default Hash values, and that would clean this code up a lot, but I still wanted to know which is preferable: an if statement without body, or unless, or something else.
This is probably the nicest:
letters = Hash.new(0)
string = "aaabbc"
string.each_char do |letter|
if letter != " "
letters[letter] += 1
end
end
# => {"a"=>3, "b"=>2, "c"=>1}
For deciding between your two examples, I would avoid adding extra-depth (more indentation). The second one is also easier to read because it's simple to follow a string of if/else statements. It's almost always preferable to have more readable code than fancy code.
You can set the default value for a hash when constructing:
letters = Hash.new(0)
...
letters[letter] = letters[letter].next
An interesting approach using this is to use some of the map / reduce methods offered by Ruby:
letters = string.chars
.reject{ |letter| letter == " " }
.each_with_object(Hash.new(0)) { |letter, memo|
memo[letter] = memo[letter].next
}

How to sort first before upcase-downcase in Ruby? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This code is almost right, but I need to sort the inputs in alphabetical order before alternating between upcase and downcase.
football_team = []
5.times do |i|
puts "Please enter a UK football team:"
team = gets.chomp
if i.even?
football_team << team.upcase
else
football_team << team.downcase
end
end
puts football_team
I cannot use each_with_index.
I need to sort the inputs in alphabetical order before alternating between upcase and downcase.
I can identify 3 parts:
collect input
sort alphabetical
upcase and downcase
Obviously, this can't be done in a single loop.
That being said, here's one way to separate your code:
Part 1:
teams = []
5.times do |i|
puts "Please enter a UK football team:"
teams << gets.chomp
end
Part 2:
teams.sort!
Part 3:
5.times do |i|
if i.even?
teams[i].upcase!
else
teams[i].downcase!
end
end
puts teams
Adapting your answer, try this:
football_team = []
5.times do |i|
puts "Please enter a UK football team:"
team = gets.chomp.downcase
football_team << team
end
final_index = football_team.size - 1
football_team.sort!
(0..final_index).each do |i|
if i.even?
football_team[i] = football_team[i].upcase
else
football_team[i] = football_team[i].downcase
end
end
p football_team

Array not working with the modulo operator [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The first code works, but I don't understand why the second one doesn't. Any insight would be appreciated. I know in this example I really don't need an array, I just wanted to get it to work for the sake of learning.
def stamps(input)
if input % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end
print stamps(8)
But this doesn't work:
array_of_numbers = [8]
def stamps(input_array)
if input_array % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end
print stamps(array_of_numbers)
Because input_array is an array and 8 is a number. Use first to retrieve the first element of the array.
array_of_numbers = [8]
def stamps(input_array)
if input_array.first % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end
print stamps(array_of_numbers)
The following function works in case the input is number or array:
def stamps(input)
input = [input] unless input.is_a?(Array)
if input.first % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end

How to get keys from hash ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The next code search if keyword appear in hash values and print yes if so,
but it works well in codeacademy console, but in my Rubymine it give me exception
NoMethodError: undefined method `keys' for nil:NilClass
I've tried to use each_key method but it was the same rusult.
arr = [
{ name: "2222", num:"4444 kod"},
{ name: "3222 kod", num:"43423444"},
{ name: "224422", num:"4442424"}
]
p = "kod"
arr.each do |frelancer|
frelancer.keys.each do |key|
if frelancer[key].split(" ").include? (p)
puts "yes"
esle
puts "no"
end
end
Can you give some advice?)
You have 2 mistakes:
You wrote esle instead of else
You are missing one end clause
Your blocks need end keyword. And else should be spelt correctly.
arr.each do |frelancer|
frelancer.keys.each do |key|
if frelancer[key].split(" ").include? (p)
puts "yes"
else
puts "no"
end
end
end

Load functions with all variable names. Is there another way? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there a better way to do this?
value = 10
train = []
storage = 12
another_var = 'apple'
def first_function(value, train, storage, another_var)
second_function(train, storage)
third_function(train, storage, another_var)
forth_function(value, another_var)
end
def third_function(train, storage, another_var)
puts 'x'
end
def second_function(train, storage)
puts 'x'
end
def forth_function(value, another_var)
puts 'x'
end
Is this the proper way to do this? Taking the values along for the ride? I'm working my way through LRTHW and I'm trying to build a game. The problem I am running into is that I have a for loop that represents turns and that acts as the game driver. Inside of that for loop it calls functions that then call more functions. Unless I load all the variables into the first function and then pass them down the chain it breaks. It's sort of neat that it blocks you from accessing variables outside of the very narrow scope, but is there a way I can override this?
You may want to use instance variables to keep them in scope without having to pass them as parameters every time.
#value = 10
#train = []
#storage = 12
#another_var = 'apple'
def first_function
second_function
third_function
fourth_function
end
def third_function
puts #another_var
end
def second_function
puts #value + #storage
end
def fourth_function
puts #train
end
I believe what you want is to be able to do all combinations of optional parameters.
Try this:
def myfunction(options={})
options = {:value => 10, :train => [], :storage => 12, :another_var => 'apple'}.merge(options)
puts options[:value]
puts options[:train]
puts options[:storage]
puts options[:another_var]
end
Example usage:
irb(main):013:0> myfunction({})
10
12
apple
=> nil
irb(main):014:0> myfunction({:value => 11, :storage => 23})
11
23
apple
=> nil

Resources