I have to set worksheet cell value on command ws['First Col'][1]= 255 for example.
I have tried this:
def [](*args)
return Column.new(self.find_column_index(args[0])) if args[0].is_a?(String) and args[1] != nil
return cell_name_to_row_col(args[0]) if args[0].is_a?(String) and args[1] == nil
(row, col) = parse_cell_args(args)
cells[[row, col]] || ''
end
class Column
def initialize(column)
#column = column
end
def []=(row, value)
self[row+1,#column] = value
self.save
end
end
It's not working.
In def [](*args), I have few ifs because for input ws['First Col'], it has to return all rows from first column, and for ws[1,2] it has to return second cell in first row for example.
I have also tried to tweak it a bit but I could not make it work.
Related
I have a rails controller and this code only loop through the first element in the metrics array? Why is that?
# /metrics/:id
def values
#metric = metrics.select do |metric|
id = metric['href'].split('/').last
p "id == params[:id] = #{id == params[:id]}" # false on the first iteration (but never gets to the next iteration
return id == params[:id]
end
p "HERE?" # We never get here!
end
You need to remove the return statement from your method, Ruby uses implicit return (see https://jtrudell.github.io/blog/ruby_return_values/), so the result of a block is the last line that is evaluated in that block, the return statement in your code is treated as a return from the values method. Your method needs to look something like:
def values
#metric = metrics.select do |metric|
metric['href'].split('/').last == params[:id]
end
end
I'm trying to implement a function that returns the first non-blank string from the variables passed to it. Unfortunately, some of these variables might be nil, so the naive approach
function first_non_empty(...)
for i, item in ipairs({...}) do
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
doesn't work: ipairs quits out as soon as it encounters a nil value. This can be fixed by changing the requirements so that the variables can't be nil, or by passing the length to the function so table length doesn't have to rely on ipairs, or by wrapping all parameters in a function so that none of them are explicitly nil
function first_non_empty_func(...)
for i, func in ipairs({...}) do
local item = func()
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
function fn(p)
local f = function() return p end
return f
end
-- change callers to first_non_empty_func(fn(a), fn(b), fn(c))
However, both of these solutions complicate the function prototype. Does there exist a function taking an ordered list of parameters, some of which may be nil, which returns the first of those parameters which is both non-nil and not an empty string?
Use table.pack, which preserves all nil entries and returns the number of entries in the n field:
function first_non_empty_pack(...)
local t = table.pack(...)
for i = 1, t.n do
local item = t[i]
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
select('#', ...) can be used to get the number of provided arguments, so here is an alternative that doesn't use table.pack:
function first_non_empty_pack(...)
for i = 1, select('#', ...) do
local item = select(i, ...)
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
Simpler approach is to use recursion. No extra tables created, etc:
function first_non_empty(item, ...)
if item ~= nil and item ~= '' then return item end
return first_non_empty(...)
end
But the list has to end with some ending marker. For example, boolean 'false', indicating there's no non-nil, nonempty strings.
I need to Add a tractor_beam instance method that takes a string description of an item as a parameter (e.g., "cow"). When called, the method should disable the shield, add the item to the inventory along with the ship's current location if it isn't too heavy to pick up (see algorithm below), enable the shield again, and return true. If the item is too heavy to pick up, the method should skip the inventory update and return false.
Algorithm:
An item is too heavy to pick up if its letters add up to more than 500. using .ord (Not very scientific, i know.) For example, the letters of cow add up to 329, so our tractor beam can abduct a cow, no problem.
My problem is that it returns nil and an empty hash, how do i break down the item to add each together?
Code:
class Spaceship
attr_accessor :name, :location, :item, :inventory
attr_reader :max_speed
def initialize (name, max_speed, location)
puts "Initializing new Spaceship"
#name = name
#max_speed = max_speed
#location = location
#item = item
#inventory = {}
end
def disable_shield
puts "Shield is off!"
end
def enable_shield
puts "Shield is on!"
end
def warp_to(location)
puts "Traveling at #{max_speed} to #{location}!"
#location = location
end
def tractor_beam(item)
disable_shield
item = item.split('')
item.each do |let|
let.ord
let + let.next
end
return item
if item > 500
enable_shield
#inventory[#location] = item
return true
else
return false
end
end
end
Driver Code:
uss_enterprise = Spaceship.new("USS Enterprise","200,000 mph", "China")
hms_anfromeda = Spaceship.new("HMS Andromeda", "108,277 mph", "China")
uss_enterprise.disable_shield
hms_anfromeda.enable_shield
p hms_anfromeda.location
hms_anfromeda.warp_to("Namibia")
p hms_anfromeda.location
hms_anfromeda.tractor_beam("cow")
p hms_anfromeda.item
Terminal:
Initializing new Spaceship
Initializing new Spaceship
Shield is off!
Shield is on!
"China"
Traveling at 108,277 mph to Namibia!
"Namibia"
Shield is off!
nil
Firstly, you have a return statement before your if conditional, so the conditional will never be ran. Remove that.
Secondly, you get the weight of the item by using ord, but you aren't assigning the value to anything:
item.each do |let|
let.ord
let + let.next
end
return item
if item > 500
This should do the trick:
item = item.split('')
weight = 0
item.each do |let|
weight += let.ord # add the ord of this letter to the weight
end
if weight > 500 # weight is now the ord of each letter of item 'cow'
enable_shield
#inventory[#location] = item
return true
else
return false
end
This line return item in your tractor_beam method will get run every time before getting to your if statement I think that is causing the problem.
Also you are not using the instance variable #item that you are created in the initialize method I think you might actually want something like this:
def tractor_beam(item)
disable_shield
#item = item.split('')
weight = 0
#item.each do |let|
weight += let.ord
end
if weight < 500
enable_shield
#inventory[#location] = #item
return true
else
return false
end
end
end
I'm a Ruby on Rails's beginner and so sorry for this stupid question but I've searched for it all day and still stuck at it :(
I've a model method to import file excel from computer to web with has 1st row contains table column, and other next rows have collection of record to save to database. I've tried to return true if it can save all records to db, else is false, like this:
Model
def self.import(file)
spreadsheet = open_spreadsheet(file) //another method to read file
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
item= find_by_id(row["id"]) || new
item.attributes = row.to_hash.slice(*accessible_attributes)
if item.invalid?{
return false;
break
}
else item.save end
end
end
And call it in Controller :
def save
if (Item.import(params[:file]))
redirect_to import_items_path, notice: t("success")
else redirect_to import_items_path, notice: t("fails")
end
end
But it didn't return true/false ( with always set "success" to flash.notice) when I imported
I've have call it to a variable like this
#test = Item.import(params[:file])
and sent it to flash.notice and found out that method always return a string like this
"2..xx" (with xx is a number of rows in file)
Did i make somethings weird to call ??? Plz help me ... thks 1st for anykind of answer
Your import method does not return true if no invalid items are encountered.
To fix this, replace:
if item.invalid?{
return false;
break
}
else taisan.save end
end
end
With:
return false if item.invalid?
taisan.save
end
true
end
Which will return false immediately an invalid item is encountered or true otherwise.
As an aside, you could keep your save function dry like this:
def save
message = if Item.import(params[:file])
"success"
else
"failure"
end
redirect_to import_items_path, notice: t(message)
end
I wanted to check if a string is palindrome or not using ruby code.
I am a starter in ruby so not too aquainted with the string methods in ruby
If you are not acquainted with Ruby's String methods, you should have a look at the documentation, it's very good. Mithun's answer already showed you the basic principle, but since you are new to Ruby, there's a couple more things to keep in mind:
*) If you have a predicate method, it's customary to name it with a trailing question mark, e.g. palindrome?.
*) Boolean expressions evaluate to a boolean, so you don't need to explicitly return true or false. Hence a short idiomatic version would be
def palindrome?(str)
str == str.reverse
end
*) Since Ruby's classes are open, you could add this to the string class:
class String
def palindrome?
self == self.reverse
end
end
*) If you don't want to monkey-patch String, you can directly define the method on single object (or use a module and Object#extend):
foo = "racecar"
def foo.palindrome?
self == self.reverse
end
*) You might want to make the palindrome check a bit more complex, e.g. when it comes to case or whitespace, so you are also able to detect palindromic sentences, capitalized words like "Racecar" etc.
pal = "Never a foot too far, even."
class String
def palindrome?
letters = self.downcase.scan(/\w/)
letters == letters.reverse
end
end
pal.palindrome? #=> true
def check_palindromic(variable)
if variable.reverse == variable #Check if string same when reversed
puts "#{ variable } is a palindrome."
else # If string is not the same when reversed
puts "#{ variable } is not a palindrome."
end
end
The recursive solution shows how strings can be indexed in Ruby:
def palindrome?(string)
if string.length == 1 || string.length == 0
true
else
if string[0] == string[-1]
palindrome?(string[1..-2])
else
false
end
end
end
If reading the Ruby string documentation is too boring for you, try playing around with the Ruby practice questions on CodeQuizzes and you will pick up most of the important methods.
def is_palindrome(value)
value.downcase!
# Reverse the string
reversed = ""
count = value.length
while count > 0
count -= 1
reversed += value[count]
end
# Instead of writing codes for reverse string
# we can also use reverse ruby method
# something like this value == value.reverse
if value == reversed
return "#{value} is a palindrom"
else
return "#{value} is not a palindrom"
end
end
puts "Enter a Word"
a = gets.chomp
p is_palindrome(a)
class String
def palindrome?
self.downcase == self.reverse.downcase
end
end
puts "racecar".palindrome? # true
puts "Racecar".palindrome? # true
puts "mississippi".palindrome? # false
str= gets.chomp
str_rev=""
n=1
while str.length >=n
str_rev+=str[-n]
n+=1
end
if str_rev==str
puts "YES"
else
puts "NO"
end
> first method
a= "malayalam"
if a == a.reverse
puts "a is true"
else
puts "false"
end
> second one
a= "malayalam"
a=a.split("")
i=0
ans=[]
a.count.times do
i=i+1
k=a[-(i)]
ans << k
end
if a== ans
puts "true"
else
puts "false"
end
def palindrome?(string)
string[0] == string[-1] && (string.length <= 2 || palindrome?(string[1..-2]))
end
**Solution 1** Time complexity = O(n), Space complexity = O(n)
This solution does not use the reverse method of the String class. It uses a stack(we could use an array that only allows entry and exit of elements from one end to mimic a stack).
def is_palindrome(str)
stack = []
reversed_str = ''
str.each_char do |char|
stack << char
end
until stack.empty?
reversed_str += stack.pop
end
if reversed_str == str
return true
else
return false
end
end
` Solution 2: Time complexity = O(n), Space complexity = O(1)
def inplace_reversal!(str)
i =0
j = str.length - 1
while i < j
temp = str[i]
str[i] = str[j]
str[j] = temp
i+=1
j-=1
end
return str
end
def palindrome?(str)
return "Please pass the string" if str.nil?
str = str.downcase
str_array = str.split('')
reverse_string = str_array.each_index{ |index| str_array[str_array.count - index - 1 ] end
return ("String #{str} is not a palindrome") unless str == reverse_string.join('')
"String #{str} is palindrome"
end