I've got a bit of an odd situation. If I were using a hash, this issue would be easy, however, I'm trying to use "OpenStruct" in Ruby as it provides some decently cool features.
Basically, I think I need to "constantize" a return value. I've got a regular expression:
textopts = OpenStruct.new()
textopts.recipients = []
fileparts = fhandle.read.split("<<-->>")
fileparts[0].chomp.each{|l|
if l =~ /Recipient.*/i
textopts.recipients << $&
elsif l =~ /(ServerAddress.*|EmailAddress.*)/i
textopts.$& = $&.split(":")[1]
end
}
I need a way to turn the $& for "textopts" into a valid property for filling. I've tried "constantize" and some others, but nothing works. I would assume this is possible, but perhaps I'm wrong. Obviously if I were using a hash I could just do "textopts[$&] = .....".
Any ideas?
Keeping the structure of your solution, this is one way to do it:
textopts = OpenStruct.new(:recipients => [])
fileparts = fhandle.read.split('<<-->>')
fileparts.first.chomp.each_line do |l|
case l
when /Recipient.*/i
textopts.recipients << $&
when /(Server|Email)Address.*/i
textopts.send "#{$&}=", $&.split(':')[1]
end
end
But I can't help but think that this should be a proper parser.
Related
The goal is to Rubify (ie. use some Ruby magic) the so commented code.
I'm learning Ruby and it seems every time I write a bit of code, Ruby has some magic that can simplify and make it more readable.
For example (and unrelated to the code below), instead of writing a loop to iterate over an array of integers to get the sum, in Ruby, sum = array.inject(:+) works magic.
string = 'abcd'
inn = ''
out = ''
letters = 'az'
# Rubify below, por favor
letters.split('').each do |l|
if string[/#{l}/i]
inn << l
else
out << l
end
end
Ideas?
string = 'abcd'
letters = 'az'
inn, out = letters.chars.partition{|char| string.include?(char)}.map!(&:join)
I am working on this coding challenge, and I have found that I am stuck. I thought it was possible to call the .string method on an argument that was passed in, but now I'm not sure. Everything I've found in the Ruby documentation suggests otherwise. I'd really like to figure this out without looking at the solution. Can someone help give me a push in the right direction?
# Write a method that will take a string as input, and return a new
# string with the same letters in reverse order.
# Don't use String's reverse method; that would be too simple.
# Difficulty: easy.
def reverse(string)
string_array = []
string.split()
string_array.push(string)
string_array.sort! { |x,y| y <=> x}
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts(
'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)
puts(
'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)
puts(
'reverse("") == "": ' + (reverse("") == "").to_s
)
This is the simplest one line solution, for reversing a string without using #reverse, that I have come across -
"string".chars.reduce { |x, y| y + x } # => "gnirts"
Additionally, I have never heard of the #string method, I think you might try #to_s.
Easiest way to reverse a string
s = "chetan barawkar"
b = s.length - 1
while b >= 0
print s[b]
b=b-1
end
You need to stop the search for alternative or clever methods, such as altering things so you can .sort them. It is over-thinking the problem, or in some ways avoiding thinking about the core problem you have been asked to solve.
What this test is trying to get you you to do, is understand the internals of a String, and maybe get an appreciation of how String#reverse might be implemented using the most basic string operations.
One of the most basic String operations is to get a specific character from the string. You can get the first character by calling string[0], and in general you can get the nth character (zero-indexed) by calling string[n].
In addition you can combine or build longer strings by adding them together, e.g. if you had a="hell" and b="o", then c = a + b would store "hello" in the variable c.
Using this knowledge, find a way to loop through the original string and use that to build the reverse string, one character at a time. You may also need to look up how to get the length of a string (another basic string method, which you will find in any language's string library), and how to loop through numbers in sequence.
You're on the right track converting it to an array.
def reverse(str)
str.chars.sort_by.with_index { |_, i| -i }.join
end
Here is a solution I used to reverse a string without using .reverse method :
#string = "abcde"
#l = #string.length
#string_reversed = ""
i = #l-1
while i >=0 do
#string_reversed << #string[i]
i = i-1
end
return #string_reversed
Lol, I am going through the same challenge. It may not be the elegant solution, but it works and easy to understand:
puts("Write is a string that you want to print in reverse")
#taking a string from the user
string = gets.to_s #getting input and converting into string
def reverse(string)
i = 0
abc = [] # creating empty array
while i < string.length
abc.unshift(string[i]) #populating empty array in reverse
i = i + 1
end
return abc.join
end
puts ("In reverse: " + reverse(string))
Thought i'd contribute my rookie version.
def string_reverse(string)
new_array = []
formatted_string = string.chars
new_array << formatted_string.pop until formatted_string.empty?
new_array.join
end
def reverse_str(string)
# split a string to create an array
string_arr = string.split('')
result_arr = []
i = string_arr.length - 1
# run the loop in reverse
while i >=0
result_arr.push(string_arr[i])
i -= 1
end
# join the reverse array and return as a string
result_arr.join
end
I'm working on an exercise from Codewars. The exercise is to convert a string into camel case. For example, if I had
the-stealth-warrior
I need to convert it to
theStealthWarrior
Here is my code
def to_camel_case(str)
words = str.split('-')
a = words.first
b = words[1..words.length - 1].map{|x|x.capitalize}
new_array = []
new_array << a << b
return new_array.flatten.join('')
end
I just tested it out in IRB and it works, but in codewars, it won't let me pass. I get this error message.
NoMethodError: undefined method 'map' for nil:NilClass
I don't understand this, my method was definitely right.
You need to think about edge cases. In particular in this situation if the input was an empty string, then words would be [], and so words[1..words.length - 1] would be nil.
Codewars is probably testing your code with a range of inputs, including the emplty string (and likely other odd cases).
The following works in Ruby 2 for me, even if there's only one word in the input string:
def to_camel_case(str)
str.split('-').map.with_index{|x,i| i > 0 ? x.capitalize : x}.join
end
to_camel_case("the-stealth-warrior") # => "theStealthWarrior"
to_camel_case("warrior") # => "warrior"
I know .with_index exists in 1.9.3, but I can't promise it will work with earlier versions of Ruby.
A simpler way to change the text is :
irb(main):022:0> 'the-stealth-warrior'.gsub('-', '_').camelize
=> "TheStealthWarrior"
This should do the trick:
str.gsub("_","-").split('-').map.with_index{|x,i| i > 0 ? x.capitalize : x}.join
It accounts for words with underscores
Maybe there's a test case with only one word?
In that case, you'd be trying to do a map on words[1..0], which is nil.
Add logic to handle that case and you should be fine.
In Ruby, I have an array of simple values (possible encodings):
encodings = %w[ utf-8 iso-8859-1 macroman ]
I want to keep reading a file from disk until the results are valid. I could do this:
good = encodings.find{ |enc| IO.read(file, "r:#{enc}").valid_encoding? }
contents = IO.read(file, "r:#{good}")
...but of course this is dumb, since it reads the file twice for the good encoding. I could program it in gross procedural style like so:
contents = nil
encodings.each do |enc|
if (s=IO.read(file, "r:#{enc}")).valid_encoding?
contents = s
break
end
end
But I want a functional solution. I could do it functionally like so:
contents = encodings.map{|e| IO.read(f, "r:#{e}")}.find{|s| s.valid_encoding? }
…but of course that keeps reading files for every encoding, even if the first was valid.
Is there a simple pattern that is functional, but does not keep reading the file after a the first success is found?
If you sprinkle a lazy in there, map will only consume those elements of the array that are used by find - i.e. once find stops, map stops as well. So this will do what you want:
possible_reads = encodings.lazy.map {|e| IO.read(f, "r:#{e}")}
contents = possible_reads.find {|s| s.valid_encoding? }
Hopping on sepp2k's answer: If you can't use 2.0, lazy enums can be easily implemented in 1.9:
class Enumerator
def lazy_find
self.class.new do |yielder|
self.each do |element|
if yield(element)
yielder.yield(element)
break
end
end
end
end
end
a = (1..100).to_enum
p a.lazy_find { |i| i.even? }.first
# => 2
You want to use the break statement:
contents = encodings.each do |e|
s = IO.read( f, "r:#{e}" )
s.valid_encoding? and break s
end
The best I can come up with is with our good friend inject:
contents = encodings.inject(nil) do |s,enc|
s || (c=File.open(f,"r:#{enc}").valid_encoding? && c
end
This is still sub-optimal because it continues to loop through encodings after finding a match, though it doesn't do anything with them, so it's a minor ugliness. Most of the ugliness comes from...well, the code itself. :/
I'd like to understand how the following code works:
def url
#url ||= {
"basename" => self.basename,
"output_ext" => self.output_ext,
}.inject("/:basename/") { |result, token|
result.gsub(/:#{token.first}/, token.last)
}.gsub(/\/\//, "/")
end
I know what it does; somehow it returns the url corresponding to a file located o a dir on a server. So it returns strings similar to this: /path/to/my/file.html
I understand that if #url already has a value, it will be returned and the right ||= will be discarded. I also understand that this begins creating a hash of two elements.
I also think I understand the last gsub; it replaces backslashes by slashes (to cope with windows servers, I guess).
What amazes me is the inject part. I'm not able to understand it. I have used inject before, but this one is too much for me. I don't see how this be done with an each, since I don't understand what it does.
I modified the original function slightly for this question; the original comes from this jekyll file.
Cheers!
foo.inject(bar) {|result, x| f(result,x) }
Can always be written as:
result = bar
foo.each {|x| result = f(result, x)}
result
So for your case, the version with each would look like this:
result = "/:basename/"
{
"basename" => self.basename,
"output_ext" => self.output_ext,
}.each {|token|
result = result.gsub(/:#{token.first}/, token.last)
}
result
Meaning: for all key-value-pairs in the hash, each occurrence of the key in the "/:basename/" is replaced with the value.
Perhaps splitting the code and tweaking a little helps
options = { "basename" => self.basename, "output_ext" => self.output_ext }
options.inject("/:basename") do |result, key_and_kalue|
# Iterating over the hash yields an array of two elements, which I called key_and_value
result.gsub(":#{key_and_value[0]}", key_and_value[1])
end.gsub!(//\/\/, '/')
Basically, the inject code is iterating over all your options and replacing for the actual value wherever it sees a ":key"